Monday, May 17, 2010

Sed in Unix/Linux

Sed has several commands, but most people only learn the substitute command: s. The substitute command changes all occurrences of the regular expression into a new value. A simple example is changing "day" in the "old" file to "night" in the "new" file:

sed s/day/night/ new

Or another way (for Unix beginners),

sed s/day/night/ old >new

and for those who want to test this:

echo day sed s/day/night/

This will output "night".

I didn't put quotes around the argument because this example didn't need them. If you read my earlier tutorial, you would understand why it doesn't need quotes. However, I recommend you do use quotes. If you have meta-characters in the command, quotes are necessary. And if you aren't sure, it's a good habit, and I will henceforth quote future examples to emphasize the "best practice." Using the strong (single quote) character, that would be:

sed 's/day/night/' new

I must emphasize the the sed editor changes exactly what you tell it to. So if you executed

echo Sunday sed 's/day/night/' new

This would output the word "Sunnight" bacause sed found the string "day" in the input.

There are four parts to this substitute command:

s Substitute command
/../../ Delimiter
day Regular Expression Pattern Search Pattern
night Replacement string


The search pattern is on the left hand side and the replacement string is on the right hand side.

No comments:

Post a Comment