Print pipe separated list as line by line in Korn Shell

Korn Shell in AIX 6.1

I want to print the below shown pipe (|) separated list line by line.

line=es349889|nhb882309|ts00293|snh03524|bg578835|bg37900|rnh00297|py882201|sg175883
for i in line
do
  echo "Hello $line "
done

I wanted to execute the above for loop. But i can't even set the value for variable line.

When i try to set, i am getting the below error.

#line=es349889|nhb882309|ts00293|snh03524|bg578835|bg37900|rnh00297|py882201|sg175883
ksh: sg175883:  not found
ksh: py882201:  not found
ksh: rnh00297:  not found
ksh: bg37900:  not found
ksh: bg578835:  not found
ksh: snh03524:  not found
ksh: ts00293:  not found
ksh: nhb882309:  not found

Question1. Why am i getting the above error (not found) ?

Question2. How can I print the pipe (|) separated list line by line?

Put it in quotes.

STR="a|b|c|d|e"

Otherwise, it will assume they're pipes between commands.

To print them one per line:

STR="a|b|c|d|e"
OLDIFS="$IFS"
IFS="|"
printf "%s\n" $STR
IFS="$OLDIFS"

Changing the special IFS variable to "|" makes unquoted strings split on |, so $STR becomes a b c d e which, fed into printf "%s\n", prints each string on its own line.

Then you set IFS back to normal because you probably don't want it as | all the time.

1 Like

You are genius Corona. I can't believe this was done without a loop.

str="es349889|nhb882309|ts00293"
echo "$str" | tr '|' '\n'

--ahamed