Home > Software engineering >  Shell Script sed to search for 2 different matches and replace it with different values in loop
Shell Script sed to search for 2 different matches and replace it with different values in loop

Time:07-14

In shell script i am unable to find solution for below: I have a file.txt generated as below , whose values are not fixed

    "string1","string2"
    "string4","string5"
    "string6","string9"
    "string10","string11"

I have another file:

 <abc><cde>var_1</cde><efg>var_2</efg></abc>

I need to generate output file as below

<abc><cde>string1</cde><efg>string2</efg></abc>
<abc><cde>string4</cde><efg>string5</efg></abc>
<abc><cde>string6</cde><efg>string9</efg></abc>
<abc><cde>string10</cde><efg>string11</efg></abc>

CodePudding user response:

The following sed command would do that

sed 's#"\([^"]*\)","\([^"]*\)"#<abc><cde>\1</cde><efg>\2</efg></abc>#' file.txt

What is going on here.

First we use the s#pattern#replacement# subcommand to replace every string of the input file with the replacement string.

We identify substrings in quotes as replacement text for the first and the second substitution expression referred to as \1 and \2 respectively.

CodePudding user response:

This might work for you (GNU sed):

sed -E '1{x;s/^/cat anotherFile/e;x};G
        s/.*"(.*)","(.*)".*\n(.*)var_1(.*)var_2/\3\1\4\2/' txtFile

Store anotherFile in the hold space on the first line only.

Append anotherFile to each line of txtFile and using pattern matching format the result.

  • Related