Splitting text string with "|" pipe delimiters

Hi,

I need to split the fields in some text strings into separate variables.
The fields are separated by pipes.

The strings look roughly like this:

CUSTNAME|hostname|userid|gecos field|staff|disabled||SUDO

Currently I can do it using something like cut -d"|" -f1, but when I put that into a while loop (need to go through the text file line by line), it stops working.

Here is the code I have now:

while read line
do
O1=`cut -d '|' -f1 $line`
O2=`cut -d"|" -f2 $line`
"
"
O8=`cut -d"|" -f8 $line`

echo "Field O1 is $O1"
echo "O2 is \n$O2"
"
"
echo "O8 is \n$O8"
done < listing.txt

I'm wondering if it is the presence of the pipe character which is confusing the shell.

I'm willing to try any alternative approach people can suggest. I know this should be simple, but I just can't get it to work.

Any help VERY much appreciated.
TIA, Alan.

O1=`cut -d '|' -f1 $line`
O2=`cut -d"|" -f2 $line`

In your code shell is treating $line as a file input.Thats why its failing. I have made a slight change in code.

while read line
do
O1=`echo $line |cut -d '|' -f1 `
O2=`echo $line |cut -d"|" -f2 `
O8=`echo $line |cut -d"|" -f8 `

echo "Field O1 is $O1"
echo "O2 is \n$O2"
echo "O8 is \n$O8"
done < listing.txt

can be done so

FIELDS=( F1 F2 F3 F4 F5 F6 F7 F8 )
IFS='|'
while read ${FIELDS[@]}
do
    for F in ${FIELDS[@]}
    do
        echo "$F is ${!F}"
    done
done < listing.txt

From a file you can use:

while IFS='|' read O1 O2 O3 O4 O5 O6 O7 O8; do
  echo "Field O1 is $O1" 
  echo "Field O2 is $O2"
done<listing.txt

From a string you can use:

string="CUSTNAME|hostname|userid|gecos field|staff|disabled||SUDO"
IFS='|' read O1 O2 O3 O4 O5 O6 O7 O8 <<EOF
$string
EOF

or in bash/ksh93:

IFS='|' read O1 O2 O3 O4 O5 O6 O7 O8 <<<"$string"

---------- Post updated at 08:52 ---------- Previous update was at 08:45 ----------

In ksh93/bash you can also use arrays, like so:

 IFS='|' O=( $string )
$ echo ${O[4]}
staff
$ echo ${O[0]}
CUSTNAME

Thanks for the replies amitranjansahu, frans and Scrutinizer.

amitranjansahu, I saw yours first, and tried it. That works perfectly, thanks.

frans and Scrutinizer, thanks for the alternative methods. Very interesting - I will save those for possible future situations.

You guys are great :). Cheers, Alan.