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
example:
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"
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]}"
The right way, using an array, for bash 3.x:
declare -a array
while read -r; do
array+=( "$REPLY" )
done <Testfile
See BashFAQ #6 for more in-depth discussion.
bash
has a builtin function to do that. readarray
reads lines from a stdin (which can be your file) and assigns them elements of an array:
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.
readarray
requires bash
version 4 (released in 2009), or better and is available on many modern linux systems. Debian stable, for example, currently provides bash
4.2 while RHEL6 provides 4.1. Mac OSX, though, is still usingbash
3.x.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With