Search code examples
linuxshellunixsh

How can I display the nth line from two files at the same time (with a 'while' loop in a shell script)?


I have the two files 'name.txt' and 'extensionv2.txt', and both of them are in same folder.

Both of them have the similar number of lines.

I want to get the nth line (variable line) from both files in the same time into named ex1 and nm variables.

So I created a while loop.

Everything is OK, but I can't get the nth line from using sed.

How can I do this with a shell script?

Here is my .sh file:

m=$(wc -l name.txt)
echo "m = $m"
t5="name.txt"
j=${m//$t5/}
echo "j = $j"
k=1
while [ $j -ge $k ]
do
    echo $j
    ex1=$(sed -n "$j{p;m}" extensionv2.txt)  # Print a variable line in file
    nm=$(sed -n "$j{p;m}" name.txt)
    echo "ex1 = $ex1"
    echo "nm = $nm"
    #v=echo "'$nm.$ex1'"
    j=$(($j-1))
done

I tried this, but I don't know how to get it into my code...

input="name.txt"
while IFS= read -r line
do
    echo "$line"
done < "$input"

Solution

  • With awk:

    LineNum=2
    awk -v LineNum=$LineNum 'FNR==LineNum' file1 file2 
    

    To keep output in a variable:

    var=$(awk -v LineNum=$LineNum 'FNR==LineNum' file1)