Thursday, November 15, 2012

How to substitute a character or string using sed command in Unix

If you need to substitute a character or string/s in a file in Unix use sed command in Terminal.

sed 's/string/string2/' file.txt >file2.txt

This command will set sed in a substitute mode (s), and it will substitute string with string2 in every line in file.txt and save the output in file2.txt

If string is present two or more times in the line it will be substituted only in the firsts occurense and then the sed command will move to the next line. So in this case write g to specify to sed to do the substitution globally.

sed 's/string/string2/g' file.txt >file2.txt

To substitute a character or string with a new line separste the command in two lines:

sed 's/,/\                                                                
n/g' file.txt > ile2.txt

This command will substitute every "," with a new line.

If you want to give multiple substitute commands in one go use -e

sed -e 's/string1/string2/g' -e 's/string3/string4/g' file.txt >file2.txt

No comments:

Post a Comment