如何删除BASH中包含少于两个/的所有行?

时间:2014-12-02 22:46:59

标签: bash sed grep

如何删除仅包含一个或不包含/的文件中的所有行?例如,file.txt

This / line contains/ more than / one of the characters/.
This / line contains just one.
This / line/ also has/too many/.

输出结果为:

This / line contains/ more than / one of the characters/.
This / line/ also has/too many/.

我试过了grep ^[^/]*/*[^/]$ file.txt,但这似乎打印了所有内容。

5 个答案:

答案 0 :(得分:5)

试试这个:

awk -F/ 'NF>2' file

试验:

kent$ (master|✔) echo "This / line contains/ more than / one of the characters/.
dquote> This / line contains just one.
dquote> This / line/ also has/too many/."|awk -F/ 'NF>2'
This / line contains/ more than / one of the characters/.
This / line/ also has/too many/.

答案 1 :(得分:4)

你离我太远了:

grep '/.*/' <<.eof
This / line contains/ more than / one of the characters/.
This / line contains just one.
This / line/ also has/too many/.
.eof

结果:

This / line contains/ more than / one of the characters/.
This / line/ also has/too many/.

但我也喜欢Kent的解决方案: - )

答案 2 :(得分:3)

echo "This / line contains/ more than / one of the characters/.
This / line contains just one.
This / line/ also has/too many/." \
| sed -n '\@/.*/@p'

输出

This / line contains/ more than / one of the characters/.
This / line/ also has/too many/.

-n表示默认情况下不打印。 sed中的正则表达式查找具有多个/字符的行并打印它们。

Sed是一个变量工具,可能不喜欢\中的前导\@字符,所以如果收到错误消息,只需使用sed '@/.*@d'

IHTH

答案 3 :(得分:1)

另一种方式:

perl -ne '
 chomp;
 if ( ( $n1 = () = $_ =~ /\//g) > 1 ) { 
    print "$_\n";
 }' afile.txt

答案 4 :(得分:1)

这是另一个awk版本:

awk 'gsub(/\//,"&")>1' file
This / line contains/ more than / one of the characters/.
This / line/ also has/too many/.

它尝试与自己交换/gsub的输出是命中数。