2

I am now having two text files with some of the lines beginning with the same pattern. For example,

File A

1Mo 1,1 I love you.
1Mo 1,2 I like you.
Hi 23,3 I am hungry.
Hi 23,4 I am foolish.

File B

1Mo 1,1 Ich liebe dich.
1Mo 1,2 Ich mag dich.
Hi 23,5 Ich habe Durst.
Hi 23,6 Ich bin neu.

File A and File B have two lines starting with the same pattern "1Mo 1,1" and "1Mo 1,2", respectively. My expected output is like this:

1Mo 1,1 I love you.
1Mo 1,2 I like you.
1Mo 1,1 Ich liebe dich.
1Mo 1,2 Ich mag dich.

My idea is that I should use grep to extract the beginning pattern of each line in file A then using these patterns to match each line in file B. I tried to write a grep command as follows, but it failed:

grep "^[.A-z]*\s[.]*\s" file A > extract.txt

This is the command I searched the community and adapted to use for the string matching in file B:

while read string; do grep "$string" file B; done < extract.txt

Is anybody having some idea about how to do the grep thing for pattern extraction and matching?

1

Files:

> cat a
1Mo 1,1 I love you.
1Mo 1,2 I like you.
1Mo 1,3 I am hungry.
1Mo 1,4 I am foolish.

> cat b
1Mo 1,1 Ich liebe dich.
1Mo 1,2 Ich mag dich.
1Mo 1,5 Ich habe Durst.
1Mo 1,6 Ich bin neu.

Find the common lines that share the first two words (space separated):

> awk '{print $1 " " $2}' a > find
> grep -f find b | awk '{print $1 " " $2}' > find2

Now find all lines that match just those patterns:

> grep -f find2 a b
a:1Mo 1,1 I love you.
a:1Mo 1,2 I like you.
b:1Mo 1,1 Ich liebe dich.
b:1Mo 1,2 Ich mag dich.

Finaly, filter the filename:

> grep -f find2 a b | sed 's/^[^:]*://'
1Mo 1,1 I love you.
1Mo 1,2 I like you.
1Mo 1,1 Ich liebe dich.
1Mo 1,2 Ich mag dich.
  • Many thx! This solves my problem and I will try this on my whole file. – Frown Nov 17 '15 at 3:15
0

Grep excepts more than one argument and you could use this simple pattern by your examples.

grep -Eh '1,1|1,2' "File A" "File B"
  • Thx, but not all the lines that begin with 1.1 or 1.2. The pattern is overlapping in two files,and always changing. – Frown Nov 17 '15 at 3:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.