Delete


sed '5d'
Delete line 5

sed '/[Tt]est/d'
Delete all lines containing Test or test

sed 's/...//' data
Delete the first three characters from each line of data
 
sed 's/...$//' data
Delete the last 3 characters from each line of data

Delete all occurrences of a pattern in a file using sed command

This is a simple application of the /s flag where the target string is none.

For example, to remove all occurrences of word "line" in the above file, the sed command would be
bash-3.00# sed 's/line//' textfile.txt
This is  1
This is  2
This is  3
This is  4
This is  5
Note that the word to be replaced upon matching the pattern is none in the above command ('/s/line//') To remove all occurrences of the character space in the above input file, the sed command would be
bash-3.00# sed 's/ //g' textfile.txt
Thisisline1
Thisisline2
Thisisline3
Thisisline4
Thisisline5
Also note that if you don't use single quotes in the above sed command, then the space pattern should be enclosed in quotes for the command to work.
bash-3.00# sed s/' '//g textfile.txt
Thisisline1
Thisisline2
Thisisline3
Thisisline4
Thisisline5

 Deleting lines which matches a pattern using sed command To delete lines which matches a pattern, use the /d flag along with the pattern to be matched, for example, to delete lines matching the pattern "line 1" in the above file, the command would be
bash-3.00# sed '/line 1/d' textfile.txt
This is line 2
This is line 3
This is line 4
This is line 5
Now using the above commands, one can also delete the first and last line in a file which matches a pattern.  Deleting the first line which matches a pattern using sed command
bash-3.00# sed '/line/{1d;}' textfile.txt
This is line 2
This is line 3
This is line 4
This is line 5
In the above command, '1d' is used in braces to indicate that its a command (to delete the specific line, which matches a pattern), this is the way to separate sed flags in command/scripts.  Deleting the last line which matches a pattern using sed command
bash-3.00# sed '/line/{$d;}' textfile.txt
This is line 1
This is line 2
This is line 3
This is line 4

Comments

Popular posts from this blog

Standard Error

Shell Basic Operators.

AWK