sunni
sunni

Reputation: 23

Insert character after pattern with character exclusion using sed

I have this string of file names.

FileNames="FileName1.txtStrange-File-Name2.txt.zipAnother-FileName.txt"

What I like to do is to separate the file names by semicolon so I can iterate over it. For the .zipextension I have a working command.

I tried the following:

FileNames="${FileNames//.zip/.zip;}"
echo "$FileNames" | sed 's|.txt[^.zip]|.txt;|g'

Which works partially. It add a semicolon to the .zip as expected, but where sed matches the .txt I got the output:

FileName1.txt;trange-File-Name2.txt.zip;Another-FileName.txt

I think because of the character exclusion sed replaces the following character after the match.

I would like to have an output like this:

FileName1.txt;Strange-File-Name2.txt.zip;Another-FileName.txt

I'm not sticked to sed, but it would be fine to using it.

Upvotes: 2

Views: 1752

Answers (2)

damienfrancois
damienfrancois

Reputation: 59150

There might be a better way, but you can do it with sed like this:

$ 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

Beware that [^.zip] matches 'one char that is not ., nor z, nor i nor p'. It does not match 'a word that is not .zip'

Note the less verbose solution by @sundeep:

sed -E 's/(zip|txt)([^.])/\1;\2/g'

Upvotes: 2

ntj
ntj

Reputation: 171

sed -r 's/(\.[a-z]{3})(.)/\1;\2/g' 

would be a more generic expression.

Upvotes: 1

Related Questions