Tuesday, November 29, 2005

unix tip: one-liner find & replace string

normally people use sed to find & replace string.
eg:

$ cat test
abc def xyz 123 456 789
$ sed 's/abc/123/g' test
123 def xyz 123 456 789

but the output is sent to stdout (the screen) not to the file unless you redirect it to new file.
you can use perl to do that.
eg:

$ cat test
abc def xyz 123 456 789
$ perl -pi -e 's|abc|123|g' test
$ cat test
123 def xyz 123 456 789

to backup the original file use -pi.bak option & your original file will be saved as .bak

5 comments:

Anonymous said...

if the file has special characters, u'll need to use \

eg:
bash-2.05b$ cat test2
abc foo@domain.com def xyz 123 456 789
bash-2.05b$ perl -pi -e 's|foo\@domain.com|bar\@mydomain.com|g' test2
bash-2.05b$ cat test2
abc bar@mydomain.com def xyz 123 456 789

Anonymous said...

Search and replace recursively

$ find . -type f | xargs perl -pi -e s/oldstr/newstr/g

Marjan Jeffry said...

a pythonic approach go to linuxlah.blogspot.com

0xff said...

who says sed is only put the output unless redirected?

read the manual in detail,use -i

sed -i 's/linuxlah/mnajem/g' filename.txt

ashamril said...

mnajem, thanks for the correction, but only gnu sed has -i option, non gnu don't have.