仅当找到匹配字符串时才替换行的最后一个单词 [英] Replacing the last word of a line only if match string found

查看:24
本文介绍了仅当找到匹配字符串时才替换行的最后一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅当找到匹配的字符串时,我才想替换该行的最后一个单词.

I want to replace the last word of the line only if a matching string found.

输入文件:

 "id": 5918915, 

 "description": "Test Job - NA", 

 "revision": 5

预期输出:

 "id": 5918915, 

 "description": "Test Job - EU", 

 "revision": 5

因此,对于匹配 description 的行,用给定的词替换最后一个词.在这种情况下,在第 2 行将最后一个单词 NA", 替换为 EU",

So, for lines matching description, replace the last word with given word. In this case, in line 2 replace last word NA", with EU",

我试过了

sed -i '/"description"/s/.*/EU",//g' file_name

但它不起作用

推荐答案

sed -i -r '/^[ \t]*"description":.*/s/^(.* )NA",[\t ]*$/\1EU/'  FILE

 "id": 5918915, 
 "description": "Test Job - EU",
 "revision": 5"

为了测试,移除 -i 开关.

空白的数量不是很清楚,所以我将 [ \t]* 放置在行首和行尾,用于显示随机大小的空格和制表符.

The amount of whitespace isn't quiet clear, so I placed [ \t]* at line start and end for blanks and tabs of random size.

你的命令:

  sed -i '/"description"/s/.*/EU",//g' file_name

应该用 EU", 替换整行,而不仅仅是最后一个字符序列.

should substitute the whole line with EU",, not just the last char sequence.

-i 是 GNU-sed 的一个选项.检查您的版本并阅读精美的手册.如果您的 sed 缺乏支持,您必须将输出重定向到一个文件 sed "COMMANDS" INFILE >TMP文件;mv TMPFILE INFILE.请注意, sed "COMMANDS" INFILE >INFILE 不起作用,但立即销毁 INFILE;一个流行的、聪明的但功能失调的想法.我也有过.:)

The -i is an option of GNU-sed. Check your version and read the fine manual. If your sed lacks support, you have to redirect the output to a file sed "COMMANDS" INFILE > TMPFILE; mv TMPFILE INFILE. Note, that sed "COMMANDS" INFILE > INFILE will not work, but destroy the INFILE immediately; a popular, clever, but disfunctional idea. I had it too. :)

这篇关于仅当找到匹配字符串时才替换行的最后一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆