grep: outputting search strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tapmas
    New Member
    • Mar 2008
    • 1

    grep: outputting search strings

    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:

    data1.txt

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

    data2.txt

    foo bar foo bar
    barbarbarbar
    xxxxx
    yyyyy
    foofoofoo


    The command:

    grep "foo" *.txt > test.out

    returns:

    data1.txt:Hello my name is foo.
    data1.txt:Perha ps they will have food.
    data2.txt:foo bar foo bar
    data2.txt:foofo ofoo


    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.
  • oberon
    New Member
    • Mar 2008
    • 14

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

    Comment

    Working...