简体   繁体   中英

Variables from file

A text file has the following structure:

paa pee pii poo puu
baa bee bii boo buu
gaa gee gii goo guu
maa mee mii moo muu

Reading it line by line in a script is done with

while read LINE; do 
    ACTION
done < FILE

I'd need to get parameters 3 and 4 of each line into variables for ACTION. If this was manual input, $3 and $4 would do the trick. I assume awk is the tool, but I just can't wrap my head around the syntax. Halp?

read does this just fine. Pass it multiple variables and it will split on $IFS into that many fields.

while read -r one two three four five; do
    action "$three" "$four"
done <file

I added the -r option because that is usually what you want. The default behavior is a legacy oddity of limited use.

Thanks tripleee. In the meantime I managed a suitably versatile solution:

#!/bin/sh

if [ ! $1 ]; then
    echo "Which inputfile?"
    exit 
elif [ ! $2 -o ! $3 ]; then
    echo "Two position parameters required"
    exit
fi

if [ -f outfile ]; then
    mv outfile outfile.old
fi

while read -a LINE; do
    STRING="${LINE[@]}"
    if [ ${LINE[$2-1]} == ${LINE[$3-1]} ]; then # remove comment for strings
#   if [ ${LINE[$(($2-1))]} -eq ${LINE[$(($3-1))]} ]; then # remove comment for integers
        echo $STRING >> outfile
    fi
done < $1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM