Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

bash - Using sed to insert text at end of line matching string

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this :

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

Explanations

  • the sed form used here is /re/s/before/after/ where re is a regex (like a grep), s/// is substitution
  • s is 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...