使用sed在字符排除后插入字符

时间:2017-11-27 15:21:23

标签: bash sed

我有这个文件名字符串。

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,但使用它会很好。

1 个答案:

答案 0 :(得分:2)

可能有更好的方法,但您可以使用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'