Reputation: 500
I have two files: file 1:
hello.com neo.com,japan.com,example.com
news.net xyz.com, telecom.net, highlands.net, software.com
example2.com earth.net, abc.gov.uk
file 2:
neo.com
example.com
abc.gov.uk
file 2 are the search keys to search in file 1 if any of the search key is found in file 1 it should return the line of file 1 with search keys or else just the row of the file 1 like this:
hello.com neo.com, example.com
news.net
example2.com abc.gov.uk
I tried this:
grep -F -f file2 file1
The result I got is this
hello.com neo.com,japan.com,example.com
example2.com earth.net, abc.gov.uk
but I am not able to get the else part of the test. Any suggestion to fix this ?
Upvotes: 1
Views: 198
Reputation: 195289
if it is required to keep the initial order, this awk one liner could help:
awk 'NR==FNR{a[NR]=$0;next}
{l=$1;for(x in a)if($0~a[x]){l=$0;break}print l}' file2 file1
with the test data, it outputs:
hello.com neo.com,japan.com,example.com
news.net
example2.com earth.net, abc.gov.uk
Note that there could be a problem, I did regex match check in the one-liner, if in your file2 things are domains, you can escape the .(dot)
before adding them into the array a[NR]
Upvotes: 2
Reputation: 10039
{
fgrep -f file2 file1
fgrep -v -f file2 file1 | sed 's/ .*//'
}
first (f)grep take info that contain the reference, the second take the other and sed change the content. I just group the actions to allow a sort or other post action on the whole result
Upvotes: 0
Reputation: 1334
You can use the shell scripting to get the required result
#!/bin/bash
while read -r lineA <&3 read -r lineB <&4
do
line=`echo "$lineA" | grep "$lineB"`
if [ -n "$line" ] ; then
echo "$lineA";
else
echo `echo $lineA | sed 's/\([^ ]*\).*/\1/g'`
fi
done 3<1.txt 4<2.txt
Upvotes: 0