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
The
s
command stands for Replace andg
stands for global. This command will replace all theoldword
withnewword
in file.txt.
- Remove blank lines from a file.
sed '/^$/d' file.txt
^$
will match the blank lines andd
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
'2' represents line number and on this line, command will replace all
oldchar
withnewchar
in file.txt.
- Delete specific character in a file.
sed 's/char//g' file.txt
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
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
$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
This command deletes all the lines from 10 - 20 both lines included.
- Print first 10 lines of file.
sed -n '1,10p' file.txt
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
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
1i
insert the text "new-line" before the first line of the file.
Top comments (0)