Sed

From Knowledge Base
Jump to: navigation, search

sed is a command line tool for doing simple file / stream / line manipulation "scripts"

Quick Commands

Test File

1
2
3
4
5
6


Print a line number from a file
$ sed -n '97p' ~/.ssh/known_hosts
Delete a line number from a file (w/ backup copy)
$ sed -i.bak '97d' ~/.ssh/known_hosts

Explain things about sed

As I read on some comment to a comment on SO, one of the basic forms of sed (though not the very common substitution one "s/something/newthing"), has the general form of: sed -e '4d' file The general syntax is <address><command>. Where <address> can be a single line number(), or a range (<code>2,4), or regex's. <command> are things like d for delete, or p for print.

Multiple commands can be separated with a semi-colon.

sed -n '2,4p;7p' file
print lines 2-4 and line 7

Commands

  • d for delete
    • '4d' Delete line 4
  • p for print
    • '4p' Print line 4

Initial arguments

(sed -e '4d' file)

These arguments basically change the default way sed will output your file or modify the file. You put them before your "script" and I think they are supposed to be sort of adding on the "script" that follows them.


  • -e seems like the simplest, the screen will print output of the script
    • (but you cannot just '>' that to another file)
  • -n will suppress the default printing of the rest of the file to screen
    • the 'p' command will still work in your script, so this is useful for looking at just your target lines
  • -i will modify the file in place
    • this is the recommended way to have your script actually do modifications to the file
    • adding a suffix (-i.bak<code>) will make a backup copy with that suffix (file.bak) before modifying the original