2011-05-29 91 views
2

如果在Linux中使用bash脚本包含多个单词,那么我需要删除指定文件中的一行。删除包含多个单词的行

例如文件:

$ cat testfile 

This is a text 
file 

This line should be deleted 
this-should-not. 

回答

1

只是为了好玩,这里是不调用任何其他可执行文件(因为你在bash自找的)纯bash的版本:

$ while read a b; do if [ -z "$b" ]; then echo $a;fi;done <testfile 
1
awk '!/[ \t]/{print $1}' testfile 

这写着“打印不包含空格或耳线的第一要素”。 将输出空行(因为它们不包含多个单词)。

0
$ sed '/ /d' << EOF 
> This is a text 
> file 
> 
> This line should be deleted 
> this-should-not. 
> EOF 
file 

this-should-not. 
+0

这将打破,如果该文件具有制表符代替空格。如果sed regex语法允许,也许是'sed'/ [[:space:]]/d'。 – 2011-05-30 01:05:05

1

足够简单:

$ egrep -v '\S\s+\S' testfile 
+0

'grep -v'[[:space:]]''也许是为了捕获所有空白字符。 – 2011-05-29 07:44:24

+0

感谢@Lars,更新 - 但人们应该注意,这可能不适用于非GNU grep。 – 2011-05-29 07:56:46

+0

线条开始或结尾处的空格怎么样? – 2011-05-29 08:07:17

0

这应该满足您的需求:

cat filename | sed -n '/^\S*$/p' 
+1

不需要使用'猫'。 – lhf 2011-05-29 12:24:12

2

awk 'NF<=1{print}' testfile

一个字是非空白字符串。

+0

不是什么请求者问:应该是'awk'NF == 1'testfile' – 2011-05-30 01:03:57

+0

@Glenn,哎呀,对。感谢您的更正!但我认为正确的条件是'NF <= 1',所以保留* no *词的行。 – lhf 2011-05-30 01:22:09

0

如果你想编辑文件就地(没有任何备份),你也可以使用man ed

cat <<-'EOF' | ed -s testfile 
H 
,g/^[[:space:]]*/s/// 
,g/[[:space:]]*$/s/// 
,g/[[:space:]]/.d 
wq 
EOF 
相关问题