find/Replace in linux

regexxer is a nifty GUI search/replace tool featuring Perl-style regular expressions. If you need project-wide substitution and you’re tired of hacking sed command lines together, then you should definitely give it a try.

Here is how to do it in textual Linux:

1) find and replace in a single file from shell:

# sed -i 's/<find>/<replace>/g' file.ext
# sed -i 's/mehrdust/reza/g' aboutMe.txt
# sed -i 's/mehrdust/reza/g' *.txt
this replaces any occurances of mehrdust with reza in any txt file
only within the current folder. Sub-folders are not affected.)

2) Find and replace in a folder containing any number of files and sub-folders from shell:

# find . -type f -exec sed -i 's/mehrust/reza/g' {} \;
# grep -rl "X" . | xargs sed -i 's/mehrdust/reza/g'

3) Find and replace using a shell script:

      for fl in *.php; do
      mv $fl $fl.old
      sed 's/FINDSTRING/REPLACESTRING/g' $fl.old > $fl
      rm -f $fl.old
Just replace the "*.php", "FINDSTRING" and "REPLACESTRING" make it
executable and you are set.

4) Find and replace using Perl:

$ grep -rl OLDSTRING . | xargs perl -pi~ -e ‘s/OLDSTRING/NEWSTRING/’
and if you want to do it sorted, files:
$ grep -rl OLDSTRING . | sort -u | xargs perl -pi~ -e ‘s/OLDSTRING/NEWSTRING/’

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *