简体   繁体   English

文件中的变量

[英]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. 我需要将每行的参数3和4放入ACTION的变量中。 If this was manual input, $3 and $4 would do the trick. 如果这是手动输入,则$ 3和$ 4可以解决问题。 I assume awk is the tool, but I just can't wrap my head around the syntax. 我以为awk是工具,但我只是无法将语法包住。 Halp?

read does this just fine. read做就好了。 Pass it multiple variables and it will split on $IFS into that many fields. 向其传递多个变量,它将在$IFS上拆分为多个字段。

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. 我添加了-r选项,因为通常这就是您想要的。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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