Read lines starting from a line number in a bash script

33,516

Solution 1

I would use sed's addresses to start at a particular line number and print to the end of the file:

lineNumber=10
sed -n "$lineNumber"',$p' |
while read line; do
  # do stuff
done

Either that or, as Fredrik suggested, use awk:

lineNumber=10
awk "NR > $lineNumber" |
while read line; do
  # do stuff
done

Solution 2

What about something like this?

while read -r line
do
    echo "$line"
done < <(tail -n +number file.name)

It's not POSIX compatible, but try on your Bash. Of course, do what you want with $line inside while loop.
PS: Change number with yhe number line you want and file.name with the file name.

Solution 3

Just keep a counter. To print all lines after a certain line, you can do like this:

#!/bin/bash

cnt=0
while read LINE
do
    if [ "$cnt" -gt 5 ];
    then
        echo $LINE
    fi
    cnt=$((cnt+1))
done < lines.txt

or, why not use awk:

awk 'NR>5' lines.txt 

Solution 4

Some of the many ways: http://mywiki.wooledge.org/BashFAQ/011

Personally:

printf '%s\n' {1..6} | { mapfile -ts 3 x; declare -p x; }                  

Also, don't use all-caps variable names.

Share:
33,516
Gil
Author by

Gil

Chui qqn de bien dans la tempête.

Updated on July 05, 2022

Comments

  • Gil
    Gil almost 2 years

    I'm trying to read a file line by line starting from a specific line in bash. I have already used the while command to read each line of the file by incrementing the count. Can I make it start from a specific line?

    let count=0
    declare -a ARRAY
    
    while read LINE; do
    ARRAY[$count]=$LINE 
    vech=${ARRAY[$count]}
        if [...blah ..]
         then
        ...blah..
        fi 
    sleep 2 
    ((count++)) 
    done < filec.c 
    

    Any kind of help in the form of suggestions or algorithms are welcome.

    Edit: I'm trying to pass the line number as a variable . I am Grepping for a specific pattern and if found, should pass the line number starting from the pattern.