Thursday, 25 June 2009

How do you substitute strings with sed? - Use ’s/old/new’ command, so sed ’s/hello/goodbye/’ would substitute the occurrence of the word hello to goodbye.

How do you inject text with sed? - & in the substitution string defines the pattern found in the search string. As an example, here’s us trying to find a word ‘hello’ and replacing it with ‘hello and how are you’: echo ‘hello there’ | sed ’s/^hello/& and how are you/’

Can I find several patterns and refer to them in the replacement string? - Yes, use (pattern) and then refer to your patterns as \1, \2, \3 and so on.

If the string is ‘old old old’ and I run ’s/old/new’, I get ‘new old old’ as the result. I need ‘new new new‘. - You forgot the global modifier, which would replace every occurrence of the pattern with the substitution. ’s/old/new/g‘ will work.

But I want ‘old old new’ from the previous example. - Just use the numeric modifier saying you want the third occurrence to be replaced. ’s/old/new/3‘ will work.

I wrote a rather complex sed script. How do I save and run it? - Assuming that your file is named myscript1.sed, you can invoke sed -f myscript1.sed.

How do I delete trailing whitespaces from each line? - sed ’s/[ \t]*$//’ Here we’re replacing any occurrence of a space or a tab with nothing. Check sed one-liners for more examples.

How do you print just a few first lines of the file? - sed 1q will give you just the first line, sed 10q the first 10 lines.

How do you replace a pattern only if it’s found, so that it’s executed faster? - Nest the replacement statement: sed ‘/old/ s/old/new/g’ file.txt