使用 sed 在匹配字符串的行尾插入文本 [英] Using sed to insert text at end of line matching string

查看:42
本文介绍了使用 sed 在匹配字符串的行尾插入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文本文件中有一行包含分配给变量的项目列表...

I have a line in a text file containing a list of items assigned to a variable ...

ITEMS="$ITEM1 $ITEM2 $ITEM3"

我想编写一个 bash 脚本,它使用 sed 来查找匹配 ITEMS 的行并将另一个项目附加到双引号内的列表末尾,因此结果是 ...

And I would like write a bash script that uses sed to find the line matching ITEMS and append another item to the end of the list within the double quotes, so it results in ...

ITEMS="$ITEM1 $ITEM2 $ITEM3 $ITEM4"

此外,我将要添加的项目编号存储在一个变量中,假设它是 $number.所以我试图让它添加 $ITEM4$number 并让它用我分配给该变量的任何东西替换 $number ,假设在这种情况下它是数字 4 .我怎样才能最好地做到这一点?谢谢!

Furthermore, I have the number of the item to add stored in a variable, let's say it's $number. So I'm trying to get it to add $ITEM4$number and have it replace $number with whatever I assigned to that variable, let's say it's the number 4 in this case. How could I best accomplish this? Thanks!

推荐答案

$ cat file
ITEMS="$ITEM1 $ITEM2 $ITEM3"
$ number=4
$ sed "/ITEMS/s/\"$/ \$ITEM$number&/" file
ITEMS="$ITEM1 $ITEM2 $ITEM3 $ITEM4"

这篇关于使用 sed 在匹配字符串的行尾插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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