如何将特定单词后面的单词大写

yol*_*chy 5 bash sed awk

假设我想将“jumped”一词后面的第一个单词大写。下面的例子

原文:

the cow jumped over the moon
Run Code Online (Sandbox Code Playgroud)

修改案文

the cow jumped OVER the moon
Run Code Online (Sandbox Code Playgroud)

我尝试过 awk 和 sed 但似乎无法正确执行。

提前致谢

pLu*_*umo 7

循环一行中的单词,如果当前单词($(i-1))之前的单词被跳转,则用 覆盖当前单词($itoupper($i)

awk '{for (i=1; i<=NF; i++) { if ($(i-1)=="jumped") $i=toupper($i); }}1'
Run Code Online (Sandbox Code Playgroud)

您还可以将记录分隔符更改为空格以避免循环:

awk 'BEGIN{RS=ORS=" "} l=="jumped"{$0=toupper($0)} {l=$0}1'
Run Code Online (Sandbox Code Playgroud)


Raf*_*ffa 7

sed

  • 使用选项启用扩展正则表达式-E

  • 然后捕获组中的特定单词,()并在其后添加空格\s,这样您的示例特定单词将如下所示(jumped\s)

  • 然后像这样在第二组中捕获它后面的单词(\w+)

  • 然后调用这两个组\1并将\2第 2 组中的所有字母大写,\U如下所示\1\U\2

  • 然后将整个内容放入's/string1/string2/g'wheres表示搜索string1,找到后将其更改为string2andg表示全局搜索,即在所有行上搜索和替换。

  • 然后将其用于管道中的文本,如下所示:

    echo "the cow jumped over the moon" | sed -E 's/(jumped\s)(\w+)/\1\U\2/g'
    
    Run Code Online (Sandbox Code Playgroud)
  • 或者在文件中的文本上使用它,如下所示:

    sed -E 's/(jumped\s)(\w+)/\1\U\2/g' file
    
    Run Code Online (Sandbox Code Playgroud)
  • 您的示例的结果将如下所示:

    the cow jumped OVER the moon
    
    Run Code Online (Sandbox Code Playgroud)


Und*_*oud 3

根据您想要如何使用输出,您可以执行以下操作(您可以根据需要进行修改的想法):

a="the cow jumped over the moon"
Run Code Online (Sandbox Code Playgroud)
echo $a | awk '{
for(i = 1; i <= NF; i++){
if($(i-1)~/jumped/){printf toupper($i)}
else{printf $i}
printf " "}
}'
Run Code Online (Sandbox Code Playgroud)

这将输出: the cow jumped OVER the moon

这假设要修改的单词与“jumped”在同一行。