Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign each line of file to be a variable

Tags:

bash

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
like image 431
user2860658 Avatar asked Dec 09 '22 09:12

user2860658


2 Answers

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.

like image 78
Charles Duffy Avatar answered Dec 14 '22 23:12

Charles Duffy


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.

like image 44
John1024 Avatar answered Dec 14 '22 22:12

John1024