Basic sed tricks

  1. What is sed? – sed is stream editor, a Unix tool for working with streams of text data. See the awful truth about sed.
  2. 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.
  3. 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/’
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. 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

via Basic sed tricks | TechInterviews.

Tags: , , ,


Did You Enjoy This Post?

Subscribe to our blog through our RSS feed or email to receive updates on more posts like this.post on your favourite social networking or media site to let others know about this post. Help us generate more buzz by submitting/voting for this post with the following buttons.

Leave a Reply











request new questions/article: send email to freequestionbank at gmail dot com