Bash While Read From Line 2 to Line 5

This article is all about how to read files in fustigate scripts using a while loop. Reading a file is a common operation in programming. Yous should be familiar with dissimilar methods and which method is more efficient to use. In bash, a single task can be achieved in many means only there is always an optimal mode to go the chore done and we should follow it.

Before seeing how to read file contents using while loop, a quick primer on how while loop works. While loop evaluates a condition and iterates over a given set of codes when the status is true.

while [ CONDITION ] do     code block done        

Let'southward break down while loop syntax.

  • while loop should showtime with a while keyword followed by a status.
  • A condition should exist enclosed within [ ] or [[ ]]. The condition should always return true for the loop to be executed.
  • The actual block of code will be placed betwixt do and done.
NUMBER=0  while [[ $NUMBER -le 10 ]] do     echo " Welcome ${NUMBER} times "     (( NUMBER++ )) done        
While Loop
While Loop

This is a very elementary example, where the loop executes until NUMBER is not greater than 10 and prints the repeat statement.

Along with while we volition use the read command to read the contents of a file line by line. Below is the syntax of how while and read commands are combined. Now there are different ways to pass the file as input and we will see them all.

# SYNTAX while read VARIABLE do     code done        

Piping in Linux

Normally we will use the cat control to view the contents of the file from the terminal. As well, we will pipe the output of the cat command to other commands similar grep, sort, etc.

Similarly, nosotros volition apply the true cat command hither to read the content of the file and pipe it to a while loop. For demonstration, I am using /etc/passwd file but it is not advisable to mess with this file so accept a fill-in copy of this file and play with it if you desire so.

cat /etc/passwd | while read LREAD do     repeat ${LREAD} done        
Piping in Linux
Piping in Linux

Let's interruption down what will happen when the higher up code is submitted.

  • cat /etc/passwd will read the contents of the file and pass it as input through the pipage.
  • read command reads each line passed as input from cat command and stores it in the LREAD variable.
  • read control will read file contents until EOL is interpreted.

You can also use other commands like head, tail, and piping it to while loop.

head -n 5 /etc/passwd | while read LREAD practice     repeat ${LREAD} done        
Head Command
Head Control

Input Redirection in Linux

We can redirect the content of the file to while loop using the Input redirection operator (<).

while read LREAD exercise     echo ${LREAD} done < /etc/passwd | head -n 5        
Input Redirection
Input Redirection

Yous tin too store the file name to a variable and laissez passer it through a redirection operator.

FILENAME="/etc/passwd"  while read LREAD do     echo ${LREAD} done < ${FILENAME}        
Store Filename in Variable
Store Filename in Variable

Y'all can also pass file names every bit an argument to your script.

while read LREAD do     echo ${LREAD} done < $i | head -northward 5        
Store Filename as Argument
Shop Filename equally Argument

Internal Field Separator

Yous may work with different types of file formats (CSV, TXT, JSON) and you may want to split the contents of the file based on a custom delimiter. In this case, you can use "Internal field separator (IFS)" to divide the content of the file and store it in variables.

Allow me demonstrate how information technology works. Take a await at the /etc/passwd file which has a colon (:) as the delimiter. Y'all can now carve up each word from a line and store information technology in a separate variable.

In the below example, I am splitting /etc/passwd file with a colon as my separator and storing each split into dissimilar variables.

while IFS=":" read A B C D E F G do     repeat ${A}     echo ${B}     echo ${C}     echo ${D}     echo ${Due east}     echo ${F}     repeat ${Grand} washed < /etc/passwd        
Internal Field Separator
Internal Field Separator

I displayed but ane line split in the above screenshot considering screenshot size.

Empty Lines in Linux

Empty lines are not ignored when you loop through the file content. To demonstrate this I accept created a sample file with the below content. There are four lines and few empty lines, leading whitespace, trailing white space, tab characters in line 2, and some escape characters (\n and \t).

File with Empty Lines
File with Empty Lines
while read LREAD do     repeat ${LREAD} done < testfile        
Blank Line Not Ignored
Blank Line Not Ignored

Meet the event, blank line is not ignored. Also, an interesting thing to note is how white spaces are trimmed by the read command. A simple way to ignore blank lines when reading the file content is to utilise the exam operator with the -z flag which checks if the string length is zero. Now let'south repeat the same instance merely this time with a test operator.

while read LREAD exercise     if [[ ! -z $LREAD ]]     then         repeat ${LREAD}      fi done < testfile        
Blank Lines Ignored
Bare Lines Ignored

At present from the output, yous tin can see empty lines are ignored.

Escape Characters

Escape characters like \n, \t, \c will not exist printed when reading a file. To demonstrate this I am using the same sample file which has few escape characters.

File with Escape Characters
File with Escape Characters
while read LREAD practice     repeat ${LREAD} done < testfile        
Escape Character in Linux
Escape Character in Linux

You can meet from the output escape characters have lost their meaning and only north and t are printed instead of \n and \t. You tin can utilise -r to forestall backslash estimation.

while read -r LREAD practice     repeat ${LREAD} done < testfile        
Prevent Backslash Interpretation
Forestall Backslash Estimation

That's information technology for this commodity. We would love to hear back from y'all if there are any feedbacks or tips. Your feedback is what helps united states to create better content. Continue reading and keep supporting.

If You Appreciate What Nosotros Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted customs site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you lot are reading, please consider buying united states a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never catastrophe support.

barcusmindighisent.blogspot.com

Source: https://www.tecmint.com/different-ways-to-read-file-in-bash-script/

0 Response to "Bash While Read From Line 2 to Line 5"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel