Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read n lines at a time using Bash

Tags:

bash

I read the help read page, but still don't quite make sense. Don't know which option to use.

How can I read N lines at a time using Bash?

like image 351
LookIntoEast Avatar asked Nov 29 '11 16:11

LookIntoEast


People also ask

What does %% mean in Bash?

So as far as I can tell, %% doesn't have any special meaning in a bash function name. It would be just like using XX instead. This is despite the definition of a name in the manpage: name A word consisting only of alphanumeric characters and under- scores, and beginning with an alphabetic character or an under- score.

What does [- Z $1 mean in Bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.

How do you read one line at a time in Bash?

We can use the read command to read the contents of a file line by line. We use the -r argument to the read command to avoid any backslash-escaped characters. In the following example, we can see that we have an iteration over a file line by line and we store the contents of a single line in the variable “line“.

How do I read the nth line in Bash?

N is the line number that you want. For example, tail -n+7 input. txt | head -1 will print the 7th line of the file. tail -n+N will print everything starting from line N , and head -1 will make it stop after one line.


2 Answers

With Bash≥4 you can use mapfile like so:

while mapfile -t -n 10 ary && ((${#ary[@]})); do     printf '%s\n' "${ary[@]}"     printf -- '--- SNIP ---\n' done < file 

That's to read 10 lines at a time.

like image 102
gniourf_gniourf Avatar answered Oct 02 '22 10:10

gniourf_gniourf


While the selected answer works, there is really no need for the separate file handle. Just using the read command on the original handle will function fine.

Here are two examples, one with a string, one with a file:

# Create a dummy file echo -e "1\n2\n3\n4" > testfile.txt  # Loop through and read two lines at a time while read -r ONE; do     read -r TWO     echo "ONE: $ONE TWO: $TWO" done < testfile.txt  # Create a dummy variable STR=$(echo -e "1\n2\n3\n4")  # Loop through and read two lines at a time while read -r ONE; do     read -r TWO     echo "ONE: $ONE TWO: $TWO" done <<< "$STR" 

Running the above as a script would output (the same output for both loops):

ONE: 1 TWO: 2 ONE: 3 TWO: 4 ONE: 1 TWO: 2 ONE: 3 TWO: 4 
like image 35
Fmstrat Avatar answered Oct 02 '22 10:10

Fmstrat