k-man
k-man

Reputation: 1211

bash grep results with var value changing each line

I want to print to the screen my grep results, I need it to print in each line some var value and then at the same line one of grep results and so on, my lines should look like that:

CurrentURL line number:expression found

the line number and expression I already have, it's the grep command, just need help with the var in which CurrentURL will be before each grep line. thanks.

p.s

if [ "$ExpressionValue" == "email" ];then

  ExpressionValue='([[:alnum:]_.-]+@[[:alnum:]_.-]+?\.[[:alpha:].]{2,6})'
  grep -E -n -o $ExpressionValue $INDEX

else

  grep -n -o -a $ExpressionValue $INDEX

fi

and results should look like that:

{URL} {line number}:{expression}

urls will come from the var i want before each grep line, thanks

Upvotes: 0

Views: 431

Answers (1)

Zsolt Botykai
Zsolt Botykai

Reputation: 51593

You can do it easily with (g)awk like:

 export URL="SET_YOUR_URL_HERE"
 awk -v U="${URL}" '/YOUR_SEARCHPATTERN/ {print U " " NR " " $0}' INPUT_FILE

If the search pattern is dynamic:

 export URL="SET_YOUR_URL_HERE"
 awk -v U="${URL}" -v PATTERN="YOUR_SEARCHPATTERN" '$0 ~ PATTERN {print U " " NR " " $0}' INPUT_FILE

If you want to print the matching pattern only:

awk -v U="${URL}" -v PATTERN="YOUR_SEARCHPATTERN" '$0 ~ PATTERN {print U " " NR " " gensub(".*(" PATTERN ").*","\\1","g",$0)}' INPUT_FILE

Note: the above solution will print only one occurrence per line!

With grep:

 export URL="SET_YOUR_URL_HERE"
 grep -n PATTERN INPUT_FILE | while read line ; do
      printf "%s\t%s" "${URL}" "${line}"
 done

HTH

Upvotes: 3

Related Questions