猛击找到一个单词的行?

时间:2011-10-24 00:14:16

标签: regex bash sed

我正在尝试编写一个带有文件名的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和Regex的组合。

注意:我不能使用任何其他东西(它必须是一个bash脚本,没有自定义模块),所以建议这样做无济于事。

5 个答案:

答案 0 :(得分:6)

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

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

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

sed -n -E '/^\s*\S+\s*$/p'

答案 1 :(得分:2)

如果你有awk可用:awk 'NF==1'

sed:删除任何带有“非空格空间非空格”序列的行sed '/[^ ] +[^ ]/d'

答案 2 :(得分:1)

你可以使用sed删除包含char + space + 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' -

答案 3 :(得分:0)

^\s*\b[a-zA-Z.-]+\s*$

对于正则表达式部分并假设您逐行搜索文件,只有行中只有一个单词时,此正则表达式才会匹配。

答案 4 :(得分:0)

假设您可以使用grep(shell脚本中最常用的工具之一):

#!/bin/bash
grep '^ *[^ ]\+ *$' "$@"