2

I am new to Bash commands. How do I write this script to get the output shown below? NOTE: I have two files.

file1.txt - data:

i am going home
i am eating
He is working

file2.text - data:

going
eating

outputfile file3.txt

i am going home
i am eating
  • A simple grep(1) will give you what you want... – vonbrand Aug 7 '19 at 17:45
2

You can use grep:

grep -Ff file2.text file1.txt > file3.txt

-f tells it to read patterns from a file, and -F to treat the as fixed strings rather than regular expressions. If you want to match whole words (as opposed to strings), then add -w to the grep options.

| improve this answer | |
  • nitpick: I'd also add a -w here to only match full words. For instance, not match "bleating" or "outgoing", etc. – filbranden Aug 10 '19 at 0:55
  • 1
    @filbranden I did consider that - however the question title does say string rather than word (perhaps it's just malicious compliance on my part though) – steeldriver Aug 10 '19 at 1:04
  • I agree that there's quite a bit of "guessing" what the intent really was there... Oh well, your answer is great. – filbranden Aug 10 '19 at 1:07
  • 1
    @filbranden thanks for your comments - I've edited in a note about that option, hopefully that covers both possibilities – steeldriver Aug 10 '19 at 1:10

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.