How to insert new line after a specific character in scripts?

Hi,

I'm trying to add a new line after finding a specific String.

That is my string:
volumes:
-

${DIR_WORK}/loadbalancer/html:/var/www/html

and I want to change that file to:
volumes:
-

${DIR_WORK}/loadbalancer/html:/var/www/html
extra_hosts:
      - "hostname:192.168.1.4"

That my code:

 lastLine="{DIR_WORK}/loadbalancer/html:/var/www/html"
 extraHost="extra_hosts:"
 sed 's~'"${lastLine}"'~a\'"${extraHost}"'~' $file

but that do nothing

do you have an idea!?

Hi, try so

lastline='{DIR_WORK}\/loadbalancer\/html:\/var\/www\/html'
sed -i '/'"$lastline"'/ a \extra_hosts:' $file

Please always tell us what operating system and shell you're using when you start a new thread in the UNIX for Beginners Questions & Answers forum. Although many utilities are available on all BSD, Linux, and UNIX systems, the options they provide and the output they produce can vary from system to system and shell to shell. If we know what environment you're working in, it helps us make suggestions that will work in your environment without having to guess what your environment might be.

It isn't at all clear to me what you're trying to do.

Does the file you want to edit actually contain the text ${DIR_WORK} or does the file contain what the expansion of the shell variable DIR_WORK expands to?

Can that line appear more than once in a file?

Can anything else appear on that line? (It doesn't look like you're trying to only match lines that exactly match that string; it looks like you're only trying to match lines that contain that string possibly with other text before and/or after what is in your search string?)

When that line is found in a file, do you want to add two lines to thee end of that file? Or do you want to add those two lines immediately following the line you found?

By calling the variable you're searching for lastLine are you indicating that the line you're looking for should only appear as the last line in that file?

1 Like

This is a very interesting formulation of the problem! Thanks
suppose this is a real string:

l='${DIR_WORK}\/loadbalancer\/html:\/var\/www\/html'

Only after the first match:

sed -i '0,/'"$l"'/ {/'"$l"'/ a \extra_hosts:'$'\n}' testfile

or

sed -ni 's/'"$l"'/&\nexra_hosts:/;p;T;:1;n;p;b1' testfile

For example, only after the second match

sed '/'"$l"'/! b;x;s/$/\n/;/^\n\n$/! b1;x;s/.*/&\nextra_host:/;b;:1;x'

or after the third match:

sed '/'"$l"'/! b;x;s/$/\n/;/^\n\n\n$/! b1;x;s/.*/&\nextra_hosts:/;b;:1;x'

gnu bash 4.4 redhat-linux

Hi nezabudka,
There are lots of possibilities here. Why don't we wait for siamak to explain what is really wanted.

It is too late at night (actually early in the morning) for me to come up with solutions for all of the possibilities that might meet siamak's ambiguous requirements.

Cheers,
Don

1 Like