将文件的每一行分配为一个变量
问题描述:
我希望通过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.