Sed – Quick Reference

Another personal reference

Two basic forms of use.
sed [-n] [-e] 'command(s)' files
sed [-n] -f scriptfile files

First one uses inline commands. The second one uses a script file. A command like delete or print can be executed based on an address/line range or a pattern. Lets look at the commands themselves in no particular order just to recollect things. All concepts are mixed and mashed.

  1. p stands for print and it prints the lines that are specified. ‘1p’ will print the first line.
  2. '1,5 p' will print the lines from one to five.
  3. '2, +3 p' will print line 2 and the next 3 lines as well.
  4. '2, ~4 p' will print line 2 and every fourth line from that. Meaning, 2, 6, 10, 14, 18, 22…
  5. Address and Pattern matching can be used together.'/hello/, 5 p' looks for the line that has ‘hello’ and then prints five lines that follow it.
  6. '/hello/, $ p' prints from the line that has the first occurence of hello till the end
  7. '/pattern1/ /pattern2/ p' prints all the lines that contains pattern 1 upto the line that contains pattern 2.
  8. d is for deleting a line. Similar to p, for printing.
  9. w can be used to write to a file after filtering some lines. Or with no filters at all, which would make it work like a cp command.
  10. 'w newfile' will make a copy of the target file into the new file
  11. '2,5 w newfile' will just write the lines 2 to 5 of the target file to the new file. Pattern matching can also be used instead of Address matching.
  12. a can be used to append a line to a file.
  13. '4 a text to be appended' appends the text to be appended to the file after line 4.
  14. c can be used for replacing or changing patterns or lines.
  15. '4 c text line to be replaced' will replace the fourth line with the text line to be replaced. Multiple lines can be replaced with single lines as well.
  16. i stands for insert.
  17. y for translate.
  18. Syntax for y [address1[,address2]]y/list-1/list-2/.
  19. [address1[,address2]]l shows hidden characters
  20. [address]q [value] for quit
  21. [address]r file read and insert contents of file into address of the target file specified
  22. [address1[,address2]]e [command] execute bash command on the address
  23. [address1[,address2]]s/pattern/replacement/[flags] substitute command
  24. 's/Paulo Coelho/PAULO COELHO/w junk.txt' replace and write to new file

More to be added to this post.

Advertisements