AWK prints a specific line based on a search pattern

I have two sets of test.csv data.xml files.

I am trying to grep a specific field from test.csv and search for a string in data.xml. If the string is found, print the corresponding string in the test.csv file.

Example

search string - field name 3.

test.csv

111,xxx,serversugar,port90 222,yyy,servertorque,port190 333,aaa,serverastrix,port8080 422,yxy,servertorque,port290 

data.xml

 <group> <hostname>servertorque</hostname> <hostname>serverastrix</hostname></group> 

Expected Result

 222,yyy,servertorque,port190 333,aaa,serverastrix,port8080 422,yxy,servertorque,port290 
+4
source share
3 answers

with GNU sed and grep in 2 steps

 sed '/>\w\+</!d;s/.*>\(\w\+\).*/\1/' data.xml>pattern.txt grep -wf pattern.txt test.csv 

.. output:

  222, yyy, servertorque, port190
 333, aaa, serverastrix, port8080
 422, yxy, servertorque, port290
+2
source

One way: awk

 awk -v FS="[><,]" 'NR==FNR{a[$3]++;next}$3 in a' data.xml test.csv 

Test:

 $ cat data.xml <group> <hostname>servertorque</hostname> <hostname>serverastrix</hostname></group> $ cat test.csv 111,xxx,serversugar,port90 222,yyy,servertorque,port190 333,aaa,serverastrix,port8080 422,yxy,servertorque,port290 $ awk -v FS="[><,]" 'NR==FNR {a[$3]++;next} $3 in a' data.xml test.csv 222,yyy,servertorque,port190 333,aaa,serverastrix,port8080 422,yxy,servertorque,port290 
+2
source

I assume you need:

 awk -F',' '$3==<string_you_need> { print $0 }' test.csv 
0
source

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


All Articles