Modify shell variables using sed with POSIX compliance

Viewed 158

I have this shell variable:

#!/bin/sh
namelist="John Doe
Josh Franklin
John Adams
"

To delete the lines containing "John", I use:

namelist=$(sed '/John/d' <<< "$namelist")

However, after checking for POSIX compatibility from the website called Shellcheck,

it says that

In POSIX sh, here-strings are undefined.

So what would be the POSIX compliant way of modifying a variable using sed?

2 Answers

what would be the POSIX compliant way of modifying a variable using sed?

Just don't use <<< and just output it to sed.

 namelist=$(printf "%s\n" "$namelist" | sed '/John/d')

Try this

namelist="John Doe
Josh Franklin
John Adams
"
namelist=$(IFS=$'\n';for name in ${namelist}; do echo ${name} | grep -v "John"; done)

echo "${namelist}"

You can get similar output using sed aswell

namelist="John Doe
Josh Franklin
John Adams
"
namelist=$(IFS=$'\n';for name in ${namelist}; do echo ${name} | sed '/John/d'; done)

echo "${namelist}"
Related