替换特定行中的最后一个单词sed

3

I have file like

abc dog      1.0
abc cat      2.4
abc elephant 1.2

我想将包含“elephant”的行中的最后一个单词替换为我知道的字符串。

结果应该是:

abc dog      1.0
abc cat      2.4
abc elephant mystring

我用sed '/.*elephant.*/s/%/%/' $file命令,但是'%'应该替换成什么呢?
编辑: 奇怪的例子
abc dogdogdogdog      1.0
abc cat               2.4
abc elephant          1.2

最初的回答是:

现在尝试更改最后一行。


sed 's/\(elephant\)\(.*$\)/\1 mystring/' input - Fredrik Pihl
欢迎来到SO,正如评论中所提到的那样,任何问题都不应该出现不断变化的要求。此外,在您的帖子中始终添加3个东西:1-输入示例,2-预期输出示例和3-在CODE标记中展示您为解决问题付出的努力,祝学习愉快。 - RavinderSingh13
4个回答

2

编辑:为了保留空格,请尝试以下方法。

awk '
match($0,/elephant[^0-9]*/){
  val=substr($0,RSTART,RLENGTH-1)
  sub("elephant","",val)
  $NF=val "my_string"
  val=""
}
1
'  Input_file

请尝试以下方法(如果你熟悉awk的话)。最初的回答。
awk '/elephant/{$NF="my_string"} 1' Input_file

如果您想将输出保存到Input_file中,请尝试以下操作:
最初的回答
awk '/elephant/{$NF="my_string"} 1' Input_file > temp_file && mv temp_file Input_file

很好,但如果我有多个空格,awk会将其删除。如何防止awk这样做? - czaduu
你可以在我的问题末尾找到示例。 - czaduu
@czaduu,请您现在尝试一下我的编辑解决方案,然后告诉我结果好吗? - RavinderSingh13
1
太好了!谢谢!还有一个问题——我添加了编辑2。 - czaduu
1
@czaduu,那是完全不同的问题,建议不要一直更改您的问题,请为其打开一个新问题。也请从此问题中删除它,谢谢。 - RavinderSingh13
显示剩余2条评论

1
基本的。
sed '/elephant/ s/[^[:blank:]]\{1,\}$/mstring/' $file

if some space could be at the end

sed '/elephant/ s/[^[:blank:]]\{1,\}[[:blank:]*$/mystring/' $file

0

一种替换并保留空格的替代方法:

awk '/elephant/{sub(".{"length($NF)"}$","new")}7' file

以您的示例为例:

kent$ cat f
abc dog         1.0
abc cat         2.4
abc elephant    1.2

kent$ awk '/elephant/{sub(".{"length($NF)"}$","new")}7' f
abc dog         1.0
abc cat         2.4
abc elephant    new

0

在任何awk中都要强健:

$ awk '$2=="elephant"{sub(/[^[:space:]]+$/,""); $0=$0 "mystring"} 1' file
abc dog      1.0
abc cat      2.4
abc elephant mystring

请注意,与您目前所得到的其他答案不同,当目标字符串(elephant)是其他字符串的一部分或出现在第二个字段以外的某个位置或包含任何正则表达式元字符或替换字符串包含&等时,它不会失败。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接