我有这串文件名。
FileNames="FileName1.txtStrange-File-Name2.txt.zipAnother-FileName.txt"
我喜欢做的是用分号分隔文件名,这样我就可以迭代它。对于 .zip
扩展名,我有一个有效的命令。
我尝试了以下方法:
FileNames="${FileNames//.zip/.zip;}"
echo "$FileNames" | sed 's|.txt[^.zip]|.txt;|g'
部分有效。它按预期向 .zip
添加了一个分号,但在 sed 与 .txt
匹配的地方,我得到了输出:
FileName1.txt;trange-File-Name2.txt.zip;Another-FileName.txt
我认为由于字符排除,sed
在匹配后替换了以下字符。
我想要这样的输出:
FileName1.txt;Strange-File-Name2.txt.zip;Another-FileName.txt
我不坚持使用 sed
,但使用它就好了。
最佳答案
可能有更好的方法,但你可以用 sed
来实现像这样:
$ echo "FileName1.txtStrange-File-Name2.txt.zipAnother-FileName.txt" | sed 's/\(zip\|txt\)\([^.]\)/\1;\2/g'
FileName1.txt;Strange-File-Name2.txt.zip;Another-FileName.txt
请注意[^.zip]
匹配'一个不是 .
的字符,也不是z
,也不是i
也不p
'。它不匹配“不是 .zip
的单词” '
请注意@sundeep 提供的不太详细的解决方案:
sed -E 's/(zip|txt)([^.])/\1;\2/g'
关于bash - 使用 sed 在排除字符的模式后插入字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47514323/