文件中的变量

时间:2014-06-08 15:46:50

标签: bash shell variables awk

文本文件具有以下结构:

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

在脚本中逐行读取

while read LINE; do 
    ACTION
done < FILE

我需要将每行的参数3和4变为ACTION的变量。如果这是手动输入,3美元和4美元就可以了。我假设awk是工具,但我无法绕过语法。 HALP?

2 个答案:

答案 0 :(得分:2)

read这样做很好。传递多个变量,它会在$IFS分成很多字段。

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

我添加了-r选项,因为这通常是您想要的。默认行为是有限使用的遗留奇怪。

答案 1 :(得分:0)

谢谢tripleee。与此同时,我提供了一个适当的多功能解决方案:

#!/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