Look word inside file in directory

0

I am new at Bash. I have a directory tags with a lot of .txt files with similar names like this

[coral/home/tags]$ ls:
file1.txt file2.txt file3.txt file4.txt

Each .txt file contains information like this:

line1 b1
line2 b2
line3 b3
line4 b4

I want to look in every text file and find those with the word b3. If the file contains that word I want the script to write the entire line and the text file that contains such word.

This is my failed attempt:

#!/usr/bin/env                                                           
PATH=path/to/files
for x in $PATH:
do
  echo $x
done

karla

Posted 2015-04-27T01:15:45.013

Reputation: 27

you want the output to be line3 b3 filename.txt? – meatspace – 2015-04-27T02:22:53.377

yes, the line with b3 and the name of those files that contains it – karla – 2015-04-27T02:24:12.373

Answers

1

if you don't mind using grep:

in tags directory: grep -Hrn 'b3' .

  • -H prints filename (implied when multiple files being searched)
  • -r searches recursively
  • -n prints line number
  • . wildcard

Potentially interesting option: grep -C 3 'b3' path/to/files you can adjust the -Context number of lines returned before and after a match (here, it's 3).

meatspace

Posted 2015-04-27T01:15:45.013

Reputation: 1 093

I tried the command line but nothing happens, and if a try a bash script using grep it returns: grep:command not found – karla – 2015-04-27T03:07:21.953

What linux distribution are you using? You many need to install grep (it is normally standard) – Paul – 2015-04-27T03:11:39.557

a have ubuntu 12.04, and i think grep is install since when typing echo grep it returns /bin/grep – karla – 2015-04-27T03:42:35.560