Sed命令查找所有单词以大写字母开头的行
我正在学习sed命令。我写了一个命令,用大写字母替换单词的第一个字母:Sed命令查找所有单词以大写字母开头的行,sed,Sed,我正在学习sed命令。我写了一个命令,用大写字母替换单词的第一个字母: sed -e "s/\b\(.\)/\u\1/g" 但我不知道如何找到所有单词都以大写字母开头的行 例如,我的文本文件: Hello world Hello World Lorem Ipsum sample 该命令应返回一行: Hello World 对于类似的内容,您需要匹配整行,即,^…$。这适用于您的示例: sed -E '/^ *(([A-Z][^ ]*) +)*[A-Z][^ ]*$/!d' 解释 *-
sed -e "s/\b\(.\)/\u\1/g"
但我不知道如何找到所有单词都以大写字母开头的行
例如,我的文本文件:
Hello world
Hello World
Lorem Ipsum sample
该命令应返回一行:
Hello World
对于类似的内容,您需要匹配整行,即,
^…$
。这适用于您的示例:
sed -E '/^ *(([A-Z][^ ]*) +)*[A-Z][^ ]*$/!d'
解释
-在行的开头允许有可选的空格*
-匹配大写字母,后跟任意数量的非空格字符,后跟一个或多个空格。整个组可以任意重复(([A-Z][^]*)+)*
-最后一行应以大写单词结尾,后跟可选空格[A-Z][^]**
结尾处删除与正则表达式不匹配的每一行!d
sed '/\b[[:lower:]]/d' infile
\b
是GNU扩展,因此需要使用GNU。sed用于执行s/old/new/,仅此而已。对于其他任何东西,只需使用awk以实现简单性、清晰性、健壮性、可移植性、性能等
看:
每个单词以大写字母开头的行:
$ awk 'gsub(/(^| )[[:upper:]]/,"&") == NF' file
Hello World
$ awk 'gsub(/(^| )[[:upper:]]/,"&") == 2' file
Hello World
Lorem Ipsum sample
$ awk 'gsub(/(^| )[[:upper:]]/,"&") > 1' file
Hello World
Lorem Ipsum sample
Lorem ipsum Foo bar And stuff
两个单词以大写字母开头的行:
$ awk 'gsub(/(^| )[[:upper:]]/,"&") == NF' file
Hello World
$ awk 'gsub(/(^| )[[:upper:]]/,"&") == 2' file
Hello World
Lorem Ipsum sample
$ awk 'gsub(/(^| )[[:upper:]]/,"&") > 1' file
Hello World
Lorem Ipsum sample
Lorem ipsum Foo bar And stuff
超过1个单词以大写字母开头的行:
$ awk 'gsub(/(^| )[[:upper:]]/,"&") == NF' file
Hello World
$ awk 'gsub(/(^| )[[:upper:]]/,"&") == 2' file
Hello World
Lorem Ipsum sample
$ awk 'gsub(/(^| )[[:upper:]]/,"&") > 1' file
Hello World
Lorem Ipsum sample
Lorem ipsum Foo bar And stuff
以大写字母开头的字数与以小写字母开头的字数相同的行:
awk 'gsub(/(^| )[[:upper:]]/,"&") == gsub(/(^| )[[:lower:]]/,"&")' file
Hello world
Lorem ipsum Foo bar And stuff
如果/当您的需求发生变化时,尝试使用您在回答问题时得到的任何sed脚本,并在上面(或任何其他!)的情况下使用它
以上内容将适用于任何UNIX设备上任何shell中的任何awk