DEV Community

NK1FC
NK1FC

Posted on

Sed- 10 Practical Uses of Sed

sed

This command is used in order to searches through, replaces, adds, and deletes lines in a text file.

10 Practical Uses of Sed

  • Replace a specific word in a text file.
 sed 's/oldword/newword/g' file.txt
Enter fullscreen mode Exit fullscreen mode

The s command stands for Replace and g stands for global. This command will replace all the oldword with newword in file.txt.

  • Remove blank lines from a file.
 sed '/^$/d' file.txt
Enter fullscreen mode Exit fullscreen mode

^$ will match the blank lines and d represents delete the line it will delete all the blank lines in file.txt.

  • Replace characters in specific line numbers.
 sed '2s/oldchar/newchar/g' file.txt
Enter fullscreen mode Exit fullscreen mode

'2' represents line number and on this line, command will replace all oldchar with newchar in file.txt.

  • Delete specific character in a file.
 sed 's/char//g' file.txt
Enter fullscreen mode Exit fullscreen mode

char specify character to delete and //g will delete all the specified characters in file.txt.

  • Replace multiple characters in a file
sed 's/[char1char2]//g' file.txt
Enter fullscreen mode Exit fullscreen mode

Inside square brackets specify all the characters that need to be deleted in file.txt.

  • Delete the last line of a file.
sed '$d' file.txt
Enter fullscreen mode Exit fullscreen mode

$d delete the last line of a file.txt, where $ matches the last line.

  • Delete a range of lines in a file.
sed '10,20d' file.txt
Enter fullscreen mode Exit fullscreen mode

This command deletes all the lines from 10 - 20 both lines included.

  • Print first 10 lines of file.
sed -n '1,10p' file.txt
Enter fullscreen mode Exit fullscreen mode

The -n option suppresses automatic output, and 1,10p print lines from 1 to 10 inclusive.

  • Delete a range of lines in file.
sed '10,20d' file.txt
Enter fullscreen mode Exit fullscreen mode

The 10,20d command deletes lines 10 to 20 inclusive in the file.

  • Insert a line before the first line of a file.
sed '1i\new-line' file.txt
Enter fullscreen mode Exit fullscreen mode

1i insert the text "new-line" before the first line of the file.

Top comments (0)