0

I am trying to prepare a shell script to include several chained sed commands.

I am using /bin/sh in FreeBSD 12. Which seems to be POSIX compliant (see man page here).

This is what I have tried, it can be clearly seen that the behaviour is not the expected one:

$ cat testfile.txt 
<TEST>

$ cat test.sh #!/bin/sh

while read line do sed 's/<TEST>/FOO/' done <&0 $ cat testfile.txt | ./test.sh

$ cat testfile.txt | sed 's/<TEST>/FOO/' FOO

$

I guess I am missing something basic here.

M.E.
  • 599

2 Answers2

1

You're reading lines, but you're not doing anything with what you read. Try:

#!/bin/sh

while read line do printf '%s\n' "$line" | sed 's/<TEST>/FOO/' done <&0

Also you may want to change the while read line to

while IFS= read -r line || [ -n "$line" ]

to ensure that you are reading everything as cat testfile.txt | sed 's/<TEST>/FOO/' would. See

steeldriver
  • 81,074
0

In any case, while you can write complex scripts in shell, it is better to use a language designed for scripting, not interactive use. Python, Perl or Raku are my first ideas when doing something more complex than a few lines. Python is popular, and almost everywhere available, ditto Perl; Raku is an evolution/ground up redesign of Perl, not nearly as popular (yet?).

vonbrand
  • 18,253