Super_Py_Me
Super_Py_Me

Reputation: 169

GREP ; 1.Use file as input 2. Append to Every Match

Looking to match and append to match in linux/unix. Perhaps sed/awk

cat Data.txt

 RMS_QUANTITY_RT
 SMS_QUANTITY_RT

file.xml

 <!-- dec=664, SMS_QUANTITY_RT -->
 <!-- dec=664, RMS_QUANTITY_RT -->

PROJECTED RESULTS

 <!-- dec=664, SMS_QUANTITY_RT OK TO REMOVE -->
 <!-- dec=664, RMS_QUANTITY_RT OK TO REMOVE-->
grep -f Data.txt file.xml | NOT SURE how to do this part

Upvotes: 1

Views: 42

Answers (2)

glenn jackman
glenn jackman

Reputation: 247042

This works with your sample input:

awk '
    NR==FNR {ok[$1]=1; next} 
    $(NF-1) in ok {$NF = "OK TO REMOVE " $NF} 
    1
' Data.txt file.xml

The first line stores the contents of Data.txt in the keys of the ok array.
The second line adds the text if the 2nd last field is found in the array keys.
The third line prints every line in file.xml

Upvotes: 1

zzevannn
zzevannn

Reputation: 3724

You can do this all in one step using sed substitution.

sed 's/RMS_QUANTITY_RT\|SMS_QUANTITY_RT/& OK TO REMOVE/g'

I just took your two search terms and made them an 'OR' regex in sed's substitution command. If you had a ton of strings it'd likely be easier to make the list into a list of sed commands and use the -f flag to have sed read the script from a file.

Here's how this works - in sed's regex substitution, & is a special char that returns the matched string of the regex, so our sed is saying match either "RMS_QUANTITY_RT" or "SMS_QUANTITY_RT" and then replacing that with whatever it matched and the static string " OK TO REMOVE".

Give this sample input:

$ cat xml.test
<!-- dec=664, SMS_QUANTITY_RT -->
<bad tag>
value value
</bad tag>
 <!-- dec=664, RMS_QUANTITY_RT -->
<bad tag>
value value
</bad tag>

We see this output running the command:

$ sed 's/RMS_QUANTITY_RT\|SMS_QUANTITY_RT/& OK TO REMOVE/g' xml.test
<!-- dec=664, SMS_QUANTITY_RT OK TO REMOVE -->
<bad tag>
value value
</bad tag>
 <!-- dec=664, RMS_QUANTITY_RT OK TO REMOVE -->
<bad tag>
value value
</bad tag>

Modifying this to then read from a file and edit the XML in place, we use a simple loop to read the files lines then do a sed -i to do the replacement in place:

while read n; do sed -i "s/$n/& OK TO REMOVE/g" file.xml; done < Data.txt

Here you can see this working:

$ cat file.xml
<!-- dec=664, SMS_QUANTITY_RT -->
<bad tag>
value value
</bad tag>
 <!-- dec=664, RMS_QUANTITY_RT -->
<bad tag>
value value
</bad tag>

Data.txt:

$ cat Data.txt
RMS_QUANTITY_RT
SMS_QUANTITY_RT

And the content of file.xml after our code is ran:

$ while read n; do sed -i "s/$n/& OK TO REMOVE/g" file.xml; done < Data.txt
$ cat file.xml
<!-- dec=664, SMS_QUANTITY_RT OK TO REMOVE -->
<bad tag>
value value
</bad tag>
 <!-- dec=664, RMS_QUANTITY_RT OK TO REMOVE -->
<bad tag>
value value
</bad tag>

Upvotes: 1

Related Questions