如果在Linux中使用bash脚本包含多个单词,那么我需要删除指定文件中的一行。删除包含多个单词的行
例如文件:
$ cat testfile
This is a text
file
This line should be deleted
this-should-not.
如果在Linux中使用bash脚本包含多个单词,那么我需要删除指定文件中的一行。删除包含多个单词的行
例如文件:
$ cat testfile
This is a text
file
This line should be deleted
this-should-not.
只是为了好玩,这里是不调用任何其他可执行文件(因为你在bash自找的)纯bash的版本:
$ while read a b; do if [ -z "$b" ]; then echo $a;fi;done <testfile
awk '!/[ \t]/{print $1}' testfile
这写着“打印不包含空格或耳线的第一要素”。 将输出空行(因为它们不包含多个单词)。
$ sed '/ /d' << EOF
> This is a text
> file
>
> This line should be deleted
> this-should-not.
> EOF
file
this-should-not.
足够简单:
$ egrep -v '\S\s+\S' testfile
'grep -v'[[:space:]]''也许是为了捕获所有空白字符。 – 2011-05-29 07:44:24
感谢@Lars,更新 - 但人们应该注意,这可能不适用于非GNU grep。 – 2011-05-29 07:56:46
线条开始或结尾处的空格怎么样? – 2011-05-29 08:07:17
awk 'NF<=1{print}' testfile
一个字是非空白字符串。
不是什么请求者问:应该是'awk'NF == 1'testfile' – 2011-05-30 01:03:57
@Glenn,哎呀,对。感谢您的更正!但我认为正确的条件是'NF <= 1',所以保留* no *词的行。 – lhf 2011-05-30 01:22:09
如果你想编辑文件就地(没有任何备份),你也可以使用man ed
:
cat <<-'EOF' | ed -s testfile
H
,g/^[[:space:]]*/s///
,g/[[:space:]]*$/s///
,g/[[:space:]]/.d
wq
EOF
这将打破,如果该文件具有制表符代替空格。如果sed regex语法允许,也许是'sed'/ [[:space:]]/d'。 – 2011-05-30 01:05:05