NPS
NPS

Reputation: 6355

Echo something while piping stdout

I know how to pipe stdout:

./myScript | grep 'important'

Example output of the above command:

Very important output.
Only important stuff here.

But while greping I would also like to echo something each line so it looks like this:

1) Very important output.
2) Only important stuff here.

How can I do that?

Edit: Apparently, I haven't specified well enough what I want to do. Numbering of lines is just an example, I want to know in general how to add text (any text, including variables and whatnot) to pipe output. I see one can achieve that using awk '{print $0}' where $0 is the solution I'm looking for.

Are there any other ways to achieve this?

Upvotes: 0

Views: 196

Answers (3)

Walter A
Walter A

Reputation: 20002

A solution with a while loop is not suited for large files, so you should only use this solution when you do not have a lot important stuff:

i=0
while read -r line; do
   ((i++))
   printf "(%s) Look out: %s" $i "${line}"
done < <(./myScript | grep 'important')

Upvotes: 2

Andreas Louv
Andreas Louv

Reputation: 47099

If you want line numbers on the new output running from 1..n where n is number of lines in the new output:

./myScript | awk '/important/{printf("%d) %s\n", ++i, $0)}'
#                  ^ Grep part                     ^ Number starting at 1

Upvotes: 2

user1717259
user1717259

Reputation: 2863

This will number the hits from 0

./myScript | grep 'important' | awk '{printf("%d) %s\n", NR, $0)}'

1) Very important output.
2) Only important stuff here.

This will give you the line number of the hit

./myScript | grep -n 'important'

3:Very important output.
47:Only important stuff here.

Upvotes: 2

Related Questions