如果在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