0

I can replace text with the following command:

for f in $(ls some/dir); do sed 's/XXX/YYY/g' template.$f.txt; done

But when I try to use in-place replacement I fail:

sed: 1: "template.test00.types ...": undefined label 'emplate.test00.types.txt'

What am I doing wrong?

EDIT: Here is a complete minimal example:

for f in $(ls some/dir); do echo $f && cat -n some/dir/$f; done
a.txt
     1  path: XXX/725
b.txt
     1  path: XXX/615
c.txt
     1  path: XXX/931

Here is how sed works correctly without actual replacement:

for f in $(ls some/dir); do sed 's/XXX/YYY/g' some/dir/$f; done 
path: YYY/725
path: YYY/615
path: YYY/931

And here is the failure:

for f in $(ls some/dir); do sed -i 's/XXX/YYY/g' some/dir/$f; done
sed: 1: "some/dir/a.txt": unterminated substitute pattern
sed: 1: "some/dir/b.txt": unterminated substitute pattern
sed: 1: "some/dir/c.txt": unterminated substitute pattern
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
  • 1
    Oh. Actually, I'll bet I know this problem. You're on a BSD like MacOS, right? – Charles Duffy Feb 06 '23 at 14:25
  • 4
    See [Bash Pitfalls #1 (for f in $(ls *.mp3))](https://mywiki.wooledge.org/BashPitfalls#for_f_in_.24.28ls_.2A.mp3.29). Run [Shellcheck](https://www.shellcheck.net/) on your code to find this error, and many other common errors. The [Shellcheck](https://www.shellcheck.net/) report has links to more information, including how to fix errors. – pjh Feb 06 '23 at 14:25
  • 1
    Make it `sed -i '' 's/XXX/YYY/g'` -- on BSD versions of `sed`, the argument after `-i` providing a file extension for backup files is not optional. Consequently, the expression is being treated as a file extension, and the first _filename_ is being treated as a sed expression, hence your error. – Charles Duffy Feb 06 '23 at 14:25
  • 1
    [sed in-place flag that works on both Mac/BSD and Linux](https://stackoverflow.com/questions/5694228/sed-in-place-flag-that-works-both-on-mac-bsd-and-linux) is on-point. – Charles Duffy Feb 06 '23 at 14:27
  • @CharlesDuffy thanks !! the `sed -i '' 's/XXX/YYY/g'` solved it ! – OrenIshShalom Feb 06 '23 at 14:48
  • @CharlesDuffy you were right, I'm on mac ... – OrenIshShalom Feb 06 '23 at 14:49
  • BTW, there are some things you can do to make your command lines less ambiguous to reduce the chance of silent misparses like this. Adding `-e` before the expression argument helps; so does adding `--` before the filenames. Sure, you'd still have incorrect behavior if you didn't know the backup flag was mandatory, but having files created with `-e` extensions is a little more obvious than the error you actually got. :) – Charles Duffy Feb 06 '23 at 15:54

0 Answers0