By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,697 Members | 1,286 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,697 IT Pros & Developers. It's quick & easy.

grep: outputting search strings

P: 1
Newbie question -- any help very much appreciated: I want to be able to get grep (or whatever else would work) to return not only matching lines, but also the original input string:

An example may help: Suppose I have two files data1.txt and data2.txt:


Hello my name is foo.
What is your name?
Shall we meet at the bar?
Perhaps they will have food.


foo bar foo bar

The command:

grep "foo" *.txt > test.out


data1.txt:Hello my name is foo.
data1.txt:Perhaps they will have food.
data2.txt:foo bar foo bar

I would like the command to also include, at the beginning of the line, my original search string (in this case "foo"). Is this possible using grep or perhaps awk, or, something else?

Thanks in advance for your help.
Mar 9 '08 #1
Share this Question
Share on Google+
1 Reply

P: 14
one solution is to make a simple shell script. Put the following in a file called e.g. mygrep:
Expand|Select|Wrap|Line Numbers
  1. !/bin/sh
  2. search=$1 #Use first argument as searchword
  3. shift 1 #Remove searchword from argument list
  4. grep $search $* | awk -v search="`echo $search`" {'print search ": " $0'}
You can then run the script with ./mygrep foo *.txt.
Mar 29 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.