Dirk Pitt
Dirk Pitt

Reputation: 293

Bash sed text replace with weird filenames

I have a list of files in a directory where the files have spaces and ()

File1 (in parenthesis).txt
File 2 (in parenthesis).txt
File name 3.txt

And on one line in each text file is the name of the file between <short_description>

<short_description>File1 (in parenthesis)</short_description>

I need to modify it to look like this

<short_description>TEST-File1 (in parenthesis)</short_description>

But I can't seem to get it... I can print the filenames out BUT when I try and do the sed command to just replace the whole line with what I want...

for FILE in "$(find  . -type f -iname '*.txt')"
do
    sed -i "s/^<short_description> .*$/<short_description>TEST-$FILE<\/short_description>/" "$FILE"
done

... this one give me an error "sed: -e expression #1, char 54: unknown option to `s''" which I'm assuming means I haven't escaped something but honestly I have no idea what.

Can someone help?
Thank you!

Upvotes: 0

Views: 79

Answers (1)

tshiono
tshiono

Reputation: 22042

If you say for FILE in "$(find . -type f -iname '*.txt')", the all filenames fed by find are enclosed with double quotes and merged into a long single string which contains whitespaces and newlines.

I can print the filenames out

Even if you try to debug with echo "$FILE", it may look as if the filenames are properly processed. But it is not. You can see it with something like echo "***${FILE}***".

Then would you please try:

for file in *.txt
do
    sed -i "s#^\(<short_description>\)\(.*\)\(</short_description>\)#\1TEST-\2\3#" "$file"
done

Upvotes: 1

Related Questions