使用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,但是使用它是可以的。

可能有更好的方法,但是您可以使用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,也不是ip'。它不匹配'不 .zip'

的单词

请注意@sundeep的较少的详细解决方案:

sed -E 's/(zip|txt)([^.])/1;2/g'
sed -r 's/(.[a-z]{3})(.)/1;2/g' 

将是一个更通用的表达。

最新更新