Laser
Laser

Reputation: 6960

Grep order from file

I have 2 files.
In first file i have teplates that i want to found in second filed.
How i must use grep for save order like it in first file in output.
example:

file1:
a
dc
as

file2:
aadfadf
asdva
vaad
a
dccsads
asas

I use this command:
grep -f file1 file2 >> file3

Upvotes: 1

Views: 250

Answers (1)

Igor Chubin
Igor Chubin

Reputation: 64563

That would be a little bit slow but quite simple:

TEMP1=$(mktemp /tmp/grep.XXXXXXXXXXX)
TEMP2=$(mktemp /tmp/grep.XXXXXXXXXXX)
cat file2 > $TEMP1
cat file1 | while read line
do 
  grep "$line" $TEMP1
  grep -v "$line" $TEMP1 > $TEMP2
  mv $TEMP2 $TEMP1
done > result
rm $TEMP2 $TEMP1

Resulting list in result.

I use the temporary files $TEMP1 and $TEMP2 and grep -v to avoid duplicates in the result.

Upvotes: 5

Related Questions