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?
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.
$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.
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“.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With