Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script to find pattern in text file and return entire line

I need to make a bash script which loops through a bunch of .txt files in a directory, then searches each .txt for a string, and returns the entire line that string appears on

I know how to look through all the .txt files in the directory,

I just need to be pointed in the right direction for searching the file itself, and returning a line based on a match in that line

like image 546
Sally Sasquatch Avatar asked Apr 13 '11 21:04

Sally Sasquatch


People also ask

How do you read an entire line in bash?

The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line: while read -r line; do COMMAND; done < input. file.

How do I grep a line from a file?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.

How do you grep all lines after a match?

You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.

How do I search for a file in a line in bash?

Using the wc -l command is the most used and also the easiest way to find line numbers of a given file.


1 Answers

Within one dir

grep "search string" *.txt

Search or go to sub-dir

find /full/path/to/dir -name "*.txt" -exec grep "search string" {} ;\
like image 57
amit_g Avatar answered Oct 14 '22 19:10

amit_g