sed: Stream Editor for Text Manipulation

ยท 409 words ยท 2 minute read

sed (Stream Editor) is a powerful command-line tool used for manipulating text streams. It’s like a search-and-replace tool on steroids, allowing you to modify text files in various ways.

sed is a valuable tool for automating text transformations. With some practice, you’ll find it indispensable for tasks like:

  • Fixing typos in multiple files.
  • Modifying configuration files.
  • Extracting specific information from text.

sed Key Concepts ๐Ÿ”—

  • Streams: sed works on streams of text data, which can be from files, standard input, or other sources.
  • Patterns: You use patterns (often regular expressions) to match specific parts of the text.
  • Commands: sed executes commands (like substitution, deletion, insertion) on the matched text.

Common Usages of sed ๐Ÿ”—

Substitution ๐Ÿ”—

Replace all occurrences of “oldword” with “newword”:

sed 's/oldword/newword/g' input.txt
  • s: The substitution command.
  • g: Replace all occurrences on each line.

Deletion ๐Ÿ”—

Delete all lines containing the word “keyword”:

sed '/keyword/d' input.txt
  • d: The delete command.

Insertion ๐Ÿ”—

Insert a line before lines matching the pattern:

sed '/pattern/i\
This line is inserted before the pattern.' input.txt
  • i: The insert command.

Printing Lines ๐Ÿ”—

Print lines that match the pattern:

sed -n '/pattern/p' input.txt
  • -n: Suppress normal output.
  • p: Print lines that match the pattern.

More Examples ๐Ÿ”—

Replace all apple (basic regex) occurrences with mango (basic regex) in all input lines and print the result to stdout:

command | sed 's/apple/mango/g'

Execute a specific script (f)ile and print the result to stdout:

command | sed -f path/to/script_file.sed

Replace all apple (extended regex) occurrences with APPLE (extended regex) in all input lines and print the result to stdout:

command | sed -E 's/(apple)/\U\1/g'

Print just a first line to stdout:

command | sed -n '1p'

Replace all apple (basic regex) occurrences with mango (basic regex) in a file and save a backup of the original to file.bak:

sed -i bak 's/apple/mango/g' path/to/file

Notes of beginners ๐Ÿ”—

  • Start with simple commands and gradually increase complexity.
  • Use single quotes (') to enclose sed commands.
  • Refer to the sed manual for a comprehensive list of commands and options. See the manual using the command man sed, or check the online version on Github .

See also: awk , ed .

I hope this post helps you. If you know a person who can benefit from this information, send them a link of this post. If you want to get notified about new posts, follow me on YouTube , Twitter (x) , LinkedIn , and GitHub .

Share: