Quick recap of single line command to replace strings in heaps of files

I was looking at the fast way to replace strings in all related Python script files recursively at Terminal.

Here's the stand one:
$ find . -type f -name "*.py" -print | xargs sed -i 's/foo/bar/g'


xargs will combine the single line output of find and run commands with multiple
arguments, multiple times if necessary to avoid the max chars per line limit. In this case we combine xargs with sed.


Here's a variation:
$ find *.py -type f -exec sed -i "s/foo/bar/g" {} \;


This one is a bit different but may be easier to remember. It actually uses find command to output a list of files. With each one of the line, it then substitutes the filename with {} for the command line using sed for further processing which is replacing 'bar' with 'foo'. A character ';' is appended to the end of each line of command.

With this command, it would actually produce something like these:
$ sed -i "s/foo/bar/g" script1_found.py;
$ sed -i "s/foo/bar/g" script2_found.py;
$ sed -i "s/foo/bar/g" script3_found.py;
$ sed -i "s/foo/bar/g" script4_found.py;
$ sed -i "s/foo/bar/g" script5_found.py;
$ sed -i "s/foo/bar/g" script6_found.py;
...









No comments:

Post a Comment

apt install through corporate proxy

Assuming proxy service like CNTLM is up and running on Ubuntu machine, one can use apt-get to install package with specifying http proxy inf...