9

For example, I got from some command some lines

$ some-command
John
Bob
Lucy

Now I'd like to add chaining command, that modifies output.

$ some-command | other-command
Hi John Bye
Hi Bob Bye
Hi Lucy Bye

How to write other-command? (I'm a novice in bash)

15

awk

$ some-command | awk '{print "Hi "$1" Bye"}'

sed

$ some-command | sed 's/\(.*\)/Hi \1 Bye/'

Examples

Using awk:

$ echo -e "John\nBob\nLucy" | awk '{print "Hi "$1" Bye"}'
Hi John Bye
Hi Bob Bye
Hi Lucy Bye

Using sed:

$ echo -e "John\nBob\nLucy" | sed 's/\(.*\)/Hi \1 Bye/'
Hi John Bye
Hi Bob Bye
Hi Lucy Bye
  • You forgot some-command | paste -d\ <(printf '%s\n' Hi Hi Hi) - <(printf '%s\n' why Why WHY??) – kojiro Feb 5 '14 at 3:17
  • @kojiro - wasn't feeling the paste way today, thanks 8-) – slm Feb 5 '14 at 3:20
5

The code below reads line after line, storing it in variable LINE. Inside the loop, each line is written back to the standard output, with the addition of "Hi" and "Bye"

#!/bin/bash

while read LINE ; do
   echo "Hi $LINE Bye"  
done
4

Bash while loop and pipes :

echo -e "John\nBob\nLucy" | while read n; do echo "hi $n bye"; done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.