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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay