Regex Bash是否要查找包含一个单词的行?
我正在尝试编写一个bash脚本,它采用一个文件名,并返回包含一个单词的行。以下是示例文本:Regex Bash是否要查找包含一个单词的行?,regex,bash,sed,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. 我正
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脚本,没有自定义模块,因此建议这样做没有帮助
^\s*\b[a-zA-Z.-]+\s*$
对于正则表达式部分,假设您逐行搜索文件,则只有当行中只有一个单词时,此正则表达式才会匹配
对于正则表达式部分,假设您正在逐行搜索文件,则此正则表达式仅在行中只有一个单词时匹配。如果单词可以包含任何非空白字符,则:
grep -E '^\s*\S+\s*$'
或
或
如果单词可以包含任何非空白字符,则:
grep -E '^\s*\S+\s*$'
或
或
假设您可以使用shell脚本中最常用的工具之一grep:
#!/bin/bash
grep '^ *[^ ]\+ *$' "$@"
假设您可以使用shell脚本中最常用的工具之一grep:
#!/bin/bash
grep '^ *[^ ]\+ *$' "$@"
您可以使用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' -
您可以使用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' -
如果您有可用的awk:awk'NF==1'
sed:如果您有可用的awk,则删除任何具有非空格序列sed'/[^]+[^]/d'的行:awk'NF==1' sed:删除具有非空格序列sed'/[^]+[^]/d'的任何行