2011-10-24 28 views
1

我正在尝试编写一个需要文件名的bash脚本,并返回包含一个单词的行。下面是示例文本:Bash找到确切的一个单词的行吗?

This has more than one word 
There 
is exactly one word in above line. 
     White-space 
in the start of the above line doesn't matter. 
Need-some-help. 

输出:

There 
     White-space 
Need-some-help. 

我在找到使用组合SED和正则表达式。

注:我不能使用其他任何东西(它必须是bash脚本,没有自定义模块),所以建议不会有帮助。

+0

为什么不能用grep删除任何行 –

回答

6

如果字可以包含任何非空白字符,则:

grep -E '^\s*\S+\s*$' 

sed -E '/^\s*\S+\s*$/!d' 

sed -n -E '/^\s*\S+\s*$/p' 
0
^\s*\b[a-zA-Z.-]+\s*$ 

对于正则表达式的一部分,假设您正在搜索的行的文件行,如果恰好有该行一个词这个表达式将只匹配。

+0

检查的例子,这是不正确的.. –

0

假设你可以使用grep(最常见的一个在shell脚本中使用的工具):

#!/bin/bash 
grep '^ *[^ ]\+ *$' "[email protected]" 
1

那么你可以使用sed删除包含char +空格+ char的行。

#!/bin/bash 
echo "This has more than one word 
There 
is exactly one word in above line. 
     White-space 
in the start of the above line doesn't matter. 
Need-some-help." | sed '/\S \S/d' - 
1

如果您在awk可供选择:awk 'NF==1'

sed的:用“非空的空间非空”序列sed '/[^ ] +[^ ]/d'