The current script is
for r in $path/[0-9]*.tst; do
sed -i s/val1/${r%.tst}/ $path/foo.bar
sed -i s/val2/${var2}/ $path/foo.bar
sed -i s/val3/${var3}/ $path/foo.bar
sed -i s/val4/${var4}/ $path/foo.bar
cat $path/foo.bar
done
Values 2-4 work fine; however, val1 remains unchanged. This is true even when I use ${r} instead of ${r%.tst}.
Are there any glaring errors in this snippet?
The main problem is that
$r
will look likepath/file.tst
so when it's expanded (whether with or without the dot extension),sed
will see something likewhich will cause an error because the
/
in the replacement string is interpreted as the terminating/
of thesed s/pattern/replacement/
You can overcome that by choosing any other character as sed's pattern separator - choose something that's not going to be in your filename or path e.g.
@
(although of course that is a legal filename character). So(I've used double-quotes here: they will allow variable expansion while preventing other potential gotchas such as glob expansion).
As a matter of style (and efficiency) I'd suggest not making multiple
sed
calls to edit the same file - you can chain multiple replacement expressions in GNU sed with-e
e.g.or make use of the
-f scriptfile
option and use a here-document: