bash 将文件的每一行分配为一个变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22466704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:56:53  来源:igfitidea点击:

Assign each line of file to be a variable

bash

提问by user2860658

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

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

example:

例子:

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

回答by Charles Duffy

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"

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

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

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

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

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

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

See BashFAQ #6for more in-depth discussion.

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

回答by John1024

bashhas a builtin function to do that. readarrayreads lines from a stdin (which can be your file) and assigns them elements of an array:

bash有一个内置函数来做到这一点。 readarray从标准输入(可以是您的文件)读取行并为它们分配数组元素:

declare -a lines
readarray -t lines <Testfile

Thereafter, you can refer to the lines by number. The first line is "${lines[0]}"and the second is "${lines[1]}", etc.

此后,您可以按编号引用行。第一行是"${lines[0]}",第二行是"${lines[1]}",等等。

readarrayrequires bashversion 4 (released in 2009), or better and is available on many modern linux systems. Debian stable, for example, currently provides bash4.2 while RHEL6provides 4.1. Mac OSX, though, is still usingbash3.x.

readarray需要bash版本 4(2009 年发布)或更高版本,并且在许多现代 linux 系统上都可用。例如,Debian stable 目前提供bash4.2,而RHEL6提供 4.1。不过,Mac OSX 仍在使用bash3.x。