Bash loops can read the input as words or lines, but what if you needed to accept multi-line input with a single loop iteration?
In the following simple example, we randomly select a hundred lines from /var/log/messages
and count the number of characters in each line:
shuf -n 100 /var/log/messages | while read line; do wc -c <<<"${line}"; done
Let’s imagine that we needed to read this input in groups of three lines and calculate the average number of characters per line for each group. You can do this with awk
but there is a way to accomplish the task using a Bash loop:
exec 5< <(shuf -n 100 /var/log/messages) while read line1 <&5 do read line2 <&5 read line3 <&5 if [ ! -z "${line2}" ] && [ ! -z "${line3}" ] then printf '%.2f\n' $(echo "($(wc -c <<<"${line1}") + $(wc -c <<<"${line2}") + $(wc -c <<<"${line3}")) / 3" | bc) fi done exec 5<&-
Experienced Unix/Linux System Administrator with 20-year background in Systems Analysis, Problem Resolution and Engineering Application Support in a large distributed Unix and Windows server environment. Strong problem determination skills. Good knowledge of networking, remote diagnostic techniques, firewalls and network security. Extensive experience with engineering application and database servers, high-availability systems, high-performance computing clusters, and process automation.