Most useful command in linux which is "sed" :)

What is sed command?

  • The sed command is a text editor in Linux that is used to modify text files. It stands for "stream editor". It takes input from a file or a command, applies a set of editing instructions (known as a script), and outputs the result to the console or a file.

Syntax:

sed <options> <command to be executed> <file to work with sed>
  • For example, if you have a file named file.txt that contains the following text:

  •         Hello world
    
  • You can use sed to replace the word "world" with "everyone" using the following command:

sed 's/world/everyone/' file.txt
  • The output will be:
    Hello everyone

For printing only the last line of the file:

sed -n '$p' <filename>

For printing in the range:

sed -n '1,5p' <filename>

Taking backup of a file while modifying it:

sed -i.back 's/root/devops/g' /etc/passwd

sed command carries some important options:

  1. -n: This option is used to suppress the default behaviour of sed which is to print the pattern space to the standard output. When -n option is used, sed does not print anything unless specifically instructed to do so.

  2. -e: This option is used to specify a command to be executed by sed. Multiple -e options can be used to execute multiple commands.

  3. -f: This option is used to specify a file containing a set of commands to be executed by sed.

  4. -i: This option is used to edit files in place. When used with -i, sed reads the input file, applies the specified commands to it, and then overwrites the input file with the modified output.

Did you find this article valuable?

Support Gaurav-Jethuri by becoming a sponsor. Any amount is appreciated!