Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read lines starting from a line number in a bash script

Tags:

linux

grep

bash

sed

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.

like image 512
Gil Avatar asked Jun 19 '12 13:06

Gil


People also ask

How can I read line by line from a variable in bash?

The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line: while read -r line; do COMMAND; done < input. file. The -r option passed to read command prevents backslash escapes from being interpreted.

How do I read a specific line in a shell script?

Using the head and tail Commands Let's say we want to read line X. The idea is: First, we get line 1 to X using the head command: head -n X input. Then, we pipe the result from the first step to the tail command to get the last line: head -n X input | tail -1.

What is $() in bash?

$( command ) or. ` command ` Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.


1 Answers

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 
like image 169
Fredrik Pihl Avatar answered Oct 23 '22 00:10

Fredrik Pihl