Utsav
Utsav

Reputation: 5918

replace content of a file from content of another file based on condition in unix

I've a two files
File1 contents:

<tag element="abc">
<util:cons path="com.rmn.STRING">
</tag>
<tag element="xyz">
<util:cons path="com.rmn.FLOAT">
</tag>

File2 contents(two space separated columns):

JAVA CHARACTER
PYTHON INT

Desired output is to replace Strings in file1 from file2.

<tag element="JAVA"> //replace string abc by JAVA
<util:cons path="com.rmn.CHARACTER"> //replace string STRING with CHARACTER
</tag>
<tag element="PYTHON"> //replace string xyz by PYTHON
<util:cons path="com.rmn.INT"> //replace string FLOAT by INT
</tag>

I'm not sure how sed or awk can be used in this case.

Upvotes: 0

Views: 136

Answers (1)

Ed Morton
Ed Morton

Reputation: 203209

sed is for simple s/old/new/ operations, that is all. You are not simply doing s/old/new/ so you should not be considering using sed. Just use awk:

$ cat tst.awk
NR==FNR {
    tag[NR]  = $1
    util[NR] = $2
    next
}
/<tag/  { sub(/"[^"]+"/,"\""tag[++cnt]"\"") }
/<util/ { sub(/\.[^."]+"/,"."util[cnt]"\"") }
{ print }

$ awk -f tst.awk file2 file1
<tag element="JAVA">
<util:cons path="com.rmn.CHARACTER">
</tag>
<tag element="PYTHON">
<util:cons path="com.rmn.INT">
</tag>

The above will fail if the $2 values in file2 can contain backreferences (i.e. &). If that's an issue then update your question to include that.

Upvotes: 3

Related Questions