将文件的每一行分配为一个变量 [英] Assign each line of file to be a variable

查看:72
本文介绍了将文件的每一行分配为一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望通过stdin为文件的每一行分配一个特定的变量,该变量可用于引用该确切的行,例如line1,line2

I am looking to assign each line of a file, through stdin a specific variable that can be used to refer to that exact line, such as line1, line2

示例:

cat Testfile
Sample 1 -line1
Sample 2 -line2
Sample 3 -line3

推荐答案

使用离散变量执行此操作的错误方法,但正是您要求的方法:

The wrong way to do this, but exactly what you asked for, using discrete variables:

while IFS= read -r line; do
    printf -v "line$(( ++i ))" '%s' "$line"
done <Testfile
echo "$line1" # to demonstrate use of array values
echo "$line2"

对于bash 4.0或更高版本,使用数组的正确方法:

The right way, using an array, for bash 4.0 or newer:

mapfile -t array <Testfile
echo "${array[0]}" # to demonstrate use of array values
echo "${array[1]}"

对于bash 3.x,使用数组的正确方法:

The right way, using an array, for bash 3.x:

declare -a array
while read -r; do
  array+=( "$REPLY" )
done <Testfile

有关更深入的讨论,请参见 BashFAQ#6 .

See BashFAQ #6 for more in-depth discussion.

这篇关于将文件的每一行分配为一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆