I am using the time-honored construct "while read field1 field2 field3 ; do" to pull delimited fields from lines of data in a file, but there are a few places within the loop where I need to manipulate the entire, unsplit line of data. Does "while read" keep each entire record/line somewhere prior to its separating the fields -- perhaps in some special variable like $? or $0?
If not, I would either have to use "while read entireLine ; do" and then split up the fields inside the loop with cut or awk, or, use "while read var1 var2 etc. ; do" and paste the separate fields back together where a copy of the whole line is needed, neither of which is very elegant.
Suggestions as to the prettiest, most elegant, or most standard way of having my cake and eating the slices too are most appreciated. --JMF
You have to read the entire line first and then split it,
but you don't need external commands for that.
If your shell splits by default (like most shells do,
not like the Z-Shell), you could do something like this:
% bash -c '
while IFS= read -r; do
printf "entire record: %s\n" "$REPLY"
set -- $REPLY
printf "first word: %s, second word: %s\n" "$1" "$2"
done<<<"a b"
'
entire record: a b
first word: a, second word: b
One line parsing, example 3 methods, same result.
If delimeter is something else as "whitespace", then change IFS, scipt include example,
if you need use | delimeter.
#!/bin/ksh
OldIFS="$IFS"
while read line
do
echo "1___________"
#IFS="|" # set new deli
arr=($line)
#IFS="$OldIFS" # return org deli
echo "${arr[*]}"
echo "${#arr[*]}"
#
echo "2___________"
set -A arr -- $line
echo "${arr[*]}"
echo "${#arr[*]}"
# radoulov example
echo "3___________"
set -- $line
echo "$@"
echo "$#"
done