Use sed to find and replace a string in multiple files
13,082
You have a flaw in your for
loop. Remove the ls
command, and add the $f
variable as the argument to sed -i
, which will edit each filename.xml
in place:
for f in *.xml; do sed -i "s|foo|bar|g" "$f"; done
Author by
Bert
Updated on September 18, 2022Comments
-
Bert over 1 year
I'm trying to pass a list of files with a known set of characters to sed for a find and replace.
For a directory containing multiple .xml files:
ls -la file1.xml file2.xml file3.xml
Each containing a matching string:
grep -i foo * file1.xml <foo/> file2.xml <foo/> file3.xml <foo/>
Replace foo with bar using a for loop:
for f in *.xml; do ls | sed -i "s|foo|bar|g" ; done
Returns:
sed: no input files sed: no input files sed: no input files
I already figured out an alternative that works, so this is mostly for my own edification at this point.
find /dir/ -name '*.xml' -exec sed -i "s|foo|bar|g" {} \;
-
Bert almost 7 yearsBingo. This is what I was aiming for.