2

here is a practical situation.I facing some of my files where there is a common string in these files.I usually will open vi and do some thing like

:%s/text/replacement/g

and I have to do it in many files many many times. Is there some easy way to do it or some sort of alias that I can create for the same?

3 Answers 3

4

You can use find for finding the target files and then pipe it to sed:

find | xargs sed -i 's/foo/bar/g'

Only replace in .txt files:

find . -name "*.txt" -print | xargs sed -i 's/foo/bar/g'

(from this blog post)

0
4

Ah yes, time for a perl oneliner. How about this?

perl -pi -e 's/old text/new text/' file

or maybe you want to change all the *.txt files in the current directory? In that case, how about combining it with GNU parallel:

parallel perl -i.bak -pe 's/foo/bar/' ::: *.txt

With parallel, the ::: means use eveything after this as input files.

or, to change all the txt files in the current directory and below:

find . -name \*txt -print0 | parallel -q -0 perl -i.bak -pe 's/old text/new text/'

Note the -i.bak saves a backup copy of every file that you change, in case you make a mistake. You can leave that out if you are feeling dangerous.

Anyway obviously the sed answer is the standard one, but there are some fun alternative ways to do it too. Also if you have a lot of files gnu parallel will be significantly faster as it runs multiple copies in parallel (as one would hope, given the name).

1
  • this is really some new thing for me.I will test it. Mar 10, 2011 at 9:47
1

Check out sed, something like this:

sed -i 's/text/replacement/g' file

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .