Hey everyone! I am determining the best method to do what the subject of this thread says. I only have pieces to the puzzle right now. Namely this:
grep -rl "expression" . | xargs open
(I should mention that the intention is to grep through many files containing the "expression" and return the files themselves for subsequent editing.)
and this:
... | for line in source; do sed 's/expression/replacement/g' > tmp; done
Except that the issue is how to open each file, substitute, and save to the same respective files, not just save to one big tmp file. This is eluding me. I realize:
mv tmp > original_file
can be done for each case, but this seems to require a level of scripting knowledge I currently lack. Thanks for any help/suggestions/advice on this!
perl -i.bak -pe 's/this/that/g' <list of file names>
Remove the .bak files after verifying that the substitutions have been done properly.
Note : This will change the inode numbers of all the files.
1 Like
> does not append, > overwrites. So, for each file, overwrite the temp file, then overwrite the original.
If you have GNU sed, you can sed -i
to edit in-place instead of cat-ing the new file atop the old.
I don't like the look of this, editing your originals is dangerous, so as a first step BACK UP YOUR FILES. One program bug could wipe out the data of interest here.
# Step 1: Back up your files. Editing your originals is dangerous!
grep -rl "expression" . | xargs tar -zcf backup-$(date +%Y-%m-%d-%H-%M-%S).tar.gz
# Step 2: Find the files, read them in order, substitute.
grep -rl "expression" | while read FILENAME
do
sed 's/..../' "$FILENAME" > /tmp/$$
cat /tmp/$$ > "$FILENAME"
done
rm -f /tmp/$$
1 Like