sed Command in Linux

Learn via video courses
Topics Covered

Overview

The sed command is a powerful text processing tool available in Linux. It allows users to perform text transformations on a file or a stream. This article explains the syntax, options, and examples of the sed command in Linux.

Linux sed Command Syntax

The syntax for the sed command is as follows:

Where:

  • OPTIONS: The available options for the sed command
  • SCRIPT: A set of sed commands to be executed on the input file.
  • FILE: The file to be processed by the sed command.

sed Command Options:

  • -i: Edit files in place
  • -e: Add the script to the commands to be executed
  • -n: Suppress automatic printing of pattern space
  • -f: Add the contents of a script file to the commands to be executed

Example Usages

  • Substitute a pattern with another pattern in a file:

    Output:

    Explanation: This command replaces all occurrences of the pattern 'pattern' with the replacement 'replacement' in the file 'file.txt'. The 'g' flag indicates that the replacement should be global, meaning all occurrences of the pattern in the file should be replaced.

  • Print specific lines in a file:

    Output:

    Explanation: This command prints the second to fourth lines of the file 'file.txt'. The '-n' option suppresses the automatic printing of the pattern space. The 'p' command prints the pattern space.

  • Delete a specific line in a file:

    Output:

    Explanation: This command deletes the third line of the file 'file.txt'. The 'd' command deletes the pattern space.

Tips

  • Use the '-i' option with caution, as it modifies the input file directly.

  • The sed command supports regular expressions for more advanced pattern matching.

Advanced Use Cases of sed Command in Linux

  • Replace a pattern in multiple files:

    Output:

    Explanation: This command replaces all occurrences of the pattern 'pattern' with the replacement 'replacement' in all .txt files in the current directory. The '-i' option edits the files in place.

  • Insert text at the beginning of a line:

    Output:

    Explanation: This command inserts the text 'prefix' at the beginning of each line in the file 'file.txt'. The '^' character represents the beginning of a line.

  • Print lines that match a pattern:

    Output:

    Explanation: This command prints all lines that contain the pattern 'pattern' in the file 'file.txt'. The '/pattern/' regular expression matches lines that contain the pattern. The 'p' command prints the pattern space.

Conclusion

  • The sed command is a powerful text processing tool available in Linux.

  • It allows users to perform text transformations on a file or a stream.

  • The sed command supports regular expressions for more advanced pattern matching.

  • Use the '-i' option with caution, as it modifies the input file directly.