知识屋:更实用的电脑技术知识网站
所在位置:首页 > 操作系统 > linux

Sed - Delete one or more lines from a file

发布时间:2014-09-05 13:42:23作者:知识屋

Sed - Delete one or more lines from a file
 
Syntax: 
 
C代码  
sed '{[/]<n>|<string>|<regex>[/]}d' <fileName>         
sed '{[/]<adr1>[,<adr2>][/]d' <fileName>  
 
/.../=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 '3d' fileName.txt  
 
Remove the line containing the string "awk":
C代码  
sed '/awk/d' filename.txt  
 
Remove the last line:
C代码  
sed '$d' filename.txt  
 
Remove all empty lines:
C代码  
sed '/^$/d' filename.txt         
sed '/./!d' 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 '/[0-9/][0-9]*$/d' filename.txt  
 
Remove the interval between lines 7 and 9:
C代码  
sed '7,9d' filename.txt  
 
The same operation as above but replacing the address with parameters:
C代码  
sed '/-Start/,/-End/d' 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" '3d' filename.txt  
 
Task: Remove blank lines using sed
Type the following command:
C代码  
$ sed '/^$/d' input.txt > output.txt  
 
Task: Remove blank lines using grep
C代码  
$ grep -v '^$' 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 '/^$/d' $i > $i.out  
  mv  $i.out $i  
done  
 
Updated for accuracy.
(免责声明:文章内容如涉及作品内容、版权和其它问题,请及时与我们联系,我们将在第一时间删除内容,文章内容仅供参考)
收藏
  • 人气文章
  • 最新文章
  • 下载排行榜
  • 热门排行榜