Using sed to insert text into a string matching string

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

ITEMS="$ITEM1 $ITEM2 $ITEM3"

And I would like to write a bash script that uses sed to search for a string matching ITEMS and adds another element to the end of the list in double quotes, so it leads to ...

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

In addition, I have the number of the element to be added, stored in a variable, say, this is the number $. So I'm trying to get him to add $ ITEM4 $ number and replace it with the number assigned to this variable, and let it be 4 in this case. How could I do this? Thanks!

-1
source share
2 answers
$ cat file
ITEMS="$ITEM1 $ITEM2 $ITEM3"
$ number=4
$ sed "/ITEMS/s/\"$/ \$ITEM$number&/" file
ITEMS="$ITEM1 $ITEM2 $ITEM3 $ITEM4"
+2
source

:

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

  • sed /re/s/before/after/, re (, a grep), s///
  • \s - , * 0 (-)
  • & ,
  • ^, /
  • $, /
+4

Source: https://habr.com/ru/post/1627646/


All Articles