作者:喜欢在他耳边唱歌 | 来源:互联网 | 2014-05-15 00:31
Sed-DeleteoneormorelinesfromafileSyntax:C代码sed&39;{[]<n>|<string>|<regex>[]}d&39;<fileName>sed&39;{[]
Sed - Delete one or more lines from a file
Syntax:
C代码
sed &#39;{[/]||[/]}d&#39;
sed &#39;{[/]
[,][/]d&#39;
/.../=delimiters
n = line number
string = string found in in line
regex = regular expression corresponding to the searched pattern
addr = address of a line (number or pattern )
d = delete
Examples
Remove the 3rd line:
C代码
sed &#39;3d&#39; fileName.txt
Remove the line containing the string "awk":
C代码
sed &#39;/awk/d&#39; filename.txt
Remove the last line:
C代码
sed &#39;$d&#39; filename.txt
Remove all empty lines:
C代码
sed &#39;/^$/d&#39; filename.txt
sed &#39;/./!d&#39; filename.txt
Remove the line matching by a regular expression (by eliminating one containing digital characters, at least 1 digit, located at the end of the line):
C代码
sed &#39;/[0-9/][0-9]*$/d&#39; filename.txt
Remove the interval between lines 7 and 9:
C代码
sed &#39;7,9d&#39; filename.txt
The same operation as above but replacing the address with parameters:
C代码
sed &#39;/-Start/,/-End/d&#39; filename.txt
The above examples are only changed at the display of the file (stdout1= screen).
For permanent changes to the old versions (<4) use a temporary file for GNU sed using the "-i[suffix]":
C代码
sed -i".bak" &#39;3d&#39; filename.txt
Task: Remove blank lines using sed
Type the following command:
C代码
$ sed &#39;/^$/d&#39; input.txt > output.txt
Task: Remove blank lines using grep
C代码
$ grep -v &#39;^$&#39; input.txt > output.txt
Both grep and sed use special pattern ^$ that matchs the blank lines. Grep -v option means print all lines except blank line.
Let us say directory /home/me/data/*.txt has all text file. Use following for loop (shell script) to remove all blank lines from all files stored in /home/me/data directory:
C代码
#!/bin/sh
files="/home/me/data/*.txt"
for i in $files
do
sed &#39;/^$/d&#39; $i > $i.out
mv $i.out $i
done
Updated for accuracy.