1

I am working on Unix command line. I have two files. I want to cat file1.txt and grep the output in file2.txt

File1.txt

123A
223A
143A
153A
183A
123J
123P

File2.txt:

123A (TYU)
223A (RUT)
143A (EWRW) 4
153A (TGBW) 89 ()
183A (23) YHYT 
123J ikik 780
123P haja 123
XRQE haja 123
XRQE haja 909

The last 2 lines of file2.txt are not present in file1.txt

I am trying to do something like:

head file1.txt | **and ??** grep file2.txt

I tried with xargs, $variable to store it, but shell hangs or doesn't work.

Expected Output: Edited:

123A (TYU)
223A (RUT)
143A (EWRW) 4
153A (TGBW) 89 ()
183A (23) YHYT 
123J ikik 780
123P haja 123

  • 3
    Please edit your question to include the expected output. – jasonwryan Sep 12 '14 at 2:11
  • Why doesn't your expected output include 123A (TYU)? – G-Man Says 'Reinstate Monica' Sep 12 '14 at 17:14
  • @G-MAN Edited now. Sorry. – Death Metal Sep 12 '14 at 21:27
2

I'm assuming you want to search for strings that are present in file2.txt using the strings from file1.txt?

If so you can use grep's -f switch to accomplish this.

excerpt from grep's man page
  -f FILE, --file=FILE

Obtain patterns from FILE, one per line. The empty file contains zero patterns, and therefore matches nothing. (-f is specified by POSIX.)

So try the following:

$ grep -f file1.txt file2.txt 
123A (TYU)
223A (RUT)
143A (EWRW) 4
153A (TGBW) 89 ()
183A (23) YHYT 
123J ikik 780
123P haja 123

Passing a portion of file1.txt

If on the other hand you'd like to only search for a portion of the strings present in file1.txt you could use process substitution to dynamically generate a subset of file1.txt and pass that as a temporary file to grep's -f switch.

For example:
$ grep -f <(head -5 file1.txt) file2.txt 
123A (TYU)
223A (RUT)
143A (EWRW) 4
153A (TGBW) 89 ()
183A (23) YHYT 

This will take the first 5 lines from file1.txt and pass them in as a temprary file via the <(..) notation to grep.

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.