Read in specific lines in a file

I have a text file

First title line
 
name1
name2
name3
name4
(etc)
 
other lines
other lines
other lines

I want to read in this text file and parse the name1...name4 to a variable. How do I specificially read in these lines and these lines only?

var=$(awk '/name[1-4]/' file)

Try:

{
  read; read;
  read var1
  read var2
  read var3 
  read var4
} < file

Thanks Jotne...but I don't know what name1-4 will be so I don't think that command will work...

Thanks Scrutinizer....could you explain your code? also I won't know how many names there are so how do I terminate the reading until say, it comes to an empty line after the last name? Sorry I misout the detail

You need a parameter to look for.

var=$(awk 'NR>1&&NR<6' file)

This takes record 2,3,4,5 into variable

@piynik. Is assumed you wanted to put line 3-6 into variables (so it skips the first two lines and then does 4 reads). If not, you would need to be more specific, provide more details.

so in that text file, it contains a list of names starting from the 3rd line, of which I don't know how many there will be (different each run), until it ends with an empty line, followed by other lines. let say the next line after the empty line is

 expected_values: 126 

So I want to write a loop, something like

while read name
do
(some operations using $name)
done <textfile.txt

in each cycle of the loop the names are parsed to a variable $name, so name1 in first cycle, name2 in 2nd cycle and so on until it reaches the empty line.

I hope that gives enough detail in what I am trying to do.

If it is a completely empty line then I would just:

var=$( awk NR==2 RS= textfile.txt )
echo "$var"

your code seems to parse all the names to the variable $name at the same time, would it be possible to parse the name one line at a time to variable $name in a loop, until it reaches the empty line?

Quick fix:

awk NR==2 RS= textfile.txt |
while read var
do
  echo "$var"
done
1 Like
var=$(awk 'NR<3{next} NF==0{exit} 1' textfile.txt)
1 Like