0
#!/usr/bin/env bash

set -euo pipefail

while read -r line
do
  echo "line via echo:"
  echo "$line"
  echo "line via sed:"
  sed 's/w/f/g' | sed 's/f/zzzzz/g' <<< "$line"
done < /dev/stdin

The above only seems to output a single line, and I'm not sure why?

printf "123\n456\n789" | ./srScript.sh
line via echo:
123
line via sed:
123

It seems to be the second sed in the pipe, it works as expected if i remove sed 's/w/f/g' |. But why does this happen - it seems like strange behaviour?

  • 1
    Where are you expecting the first sed to get its input from? did you perhaps intend to use command grouping to redirect "$line" into the whole pipeline? – steeldriver Dec 9 '18 at 14:42
  • From <<< "$line", and I'd assume it'd pipe the output to the second sed's input? But yes () brackets seems to do the job. – Chris Stryczynski Dec 9 '18 at 14:45
0

You sed pipeline is a bit back to front:

sed 's/w/f/g' | sed 's/f/zzzzz/g' <<< "$line"

This would cause the first sed to read from standard input, i.e. your 456 and 789 strings, while the second sed would read $line (123). The pipe would stop the output from the first sed from getting anywhere as the second sed is not reading from it.

I'm assuming you'd want the first sed to read the line, while the second sed reads the output of the first one.

You would do that with either

{ sed 's/w/f/g' | sed 's/f/zzzzz/g'; } <<< "$line"

or

sed 's/w/f/g' <<<"line" | sed 's/f/zzzzz/g'

Note also that in this case, you could combine the two sed calls into a single one:

sed 'y/w/f/; s/f/zzzzz/g' <<<"$line"

or,

sed -e 'y/w/f/' -e 's/f/zzzzz/g' <<<"$line"

I've additionally changed the first expression to use the y command which replaces single characters on the whole line.

However, it's very seldom a good idea to call sed for individual lines of input. If you don't need the echo output, your script could be simplified into

#!/bin/sh
sed 'y/w/f/; s/f/zzzzz/g'

or even

#!/usr/bin/sed -f
y/w/f/
s/f/zzzzz/g

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.