Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...