Voltar ao Diminua Blog

Artigo

Mastering `sed`: A Powerful Stream Editor for Text Manipulation in Linux

Transform and process text files efficiently on the command line

Mastering `sed`: A Powerful Stream Editor for Text Manipulation in Linux

Introduction to `sed`

The Stream EDitor, commonly known as sed, is a potent command-line utility for parsing and transforming text. It's particularly useful for performing automated text replacements, deletions, insertions, and other modifications on input streams or files. Unlike interactive editors like vi or nano, sed operates on a stream of data, processing it line by line according to a script of commands. This makes it ideal for scripting and automating repetitive text manipulation tasks.

This article will guide you through the fundamental concepts and practical applications of sed, enabling you to harness its power for efficient text processing in Linux environments. We'll cover basic operations, advanced techniques, and provide examples to illustrate its versatility.

Basic `sed` Syntax and Operations

The general syntax for using sed is:

sed [OPTIONS] 'script' [input_file...]

The script is a sequence of one or more sed commands. If no input_file is specified, sed reads from standard input. By default, sed prints the processed output to standard output without modifying the original file. To modify the file in place, you can use the -i option.

The `s` Command: Substitution

The most common sed command is s for substitution. Its basic syntax is:

s/pattern/replacement/flags
  • pattern: The regular expression to search for.
  • replacement: The string to replace the matched pattern with.
  • flags: Optional modifiers that change the behavior of the substitution. The most common flag is g (global), which replaces all occurrences of the pattern on a line, not just the first one.

Example: Replacing a word globally

echo 'hello world, hello universe' | sed 's/hello/hi/g'

Output:

hi world, hi universe

The `d` Command: Deletion

The d command deletes the current line from the pattern space. It's useful for removing specific lines from a file.

Example: Deleting lines containing a specific word

sed '/error/d' logfile.txt

This command will print the contents of logfile.txt, omitting any lines that contain the word

Foto de Godfrey Atima no Pexels.