bash 使用 sed 在匹配字符串的行尾插入文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15559821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:57:04  来源:igfitidea点击:

Using sed to insert text at end of line matching string

bashsed

提问by user2150250

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

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

ITEMS="$ITEM1 $ITEM2 $ITEM3"

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 ...

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

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

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!

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

回答by Gilles Quenot

Try this :

尝试这个 :

num=4
sed "/ITEMS=/s/\"$/ $ITEM${num}\"/"

Explanations

说明

  • the sed form used here is /re/s/before/after/where reis a regex (like a grep), s///is substitution
  • \sis a space and *mean 0 ore more occurence(s)
  • &stands for the string matched in the left part of the substitution
  • ^as first character of a regex means start of string/line
  • $as last character of a regex means end of string/line
  • 这里使用的 sed 形式是/re/s/before/after/wherere是正则表达式(如 a grep),s///替换
  • \s是一个空间,*表示 0 次或更多次出现
  • &代表替换左边部分匹配的字符串
  • ^作为正则表达式的第一个字符表示字符串/行的开始
  • $因为正则表达式的最后一个字符表示字符串/行的结尾

回答by Ed Morton

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