Bash Read File Line 3 to Variable
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 different methods and which method is more than efficient to use. In bash, a unmarried job tin be achieved in many means but at that place is always an optimal way to go the task washed and we should follow it.
Earlier 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 condition is truthful.
while [ CONDITION ] practise code block washed
Permit's break downward while loop syntax.
- while loop should start with a while keyword followed past a status.
- A condition should be enclosed within [ ] or [[ ]]. The condition should ever return true for the loop to be executed.
- The actual block of lawmaking will exist placed between exercise and done.
NUMBER=0 while [[ $NUMBER -le ten ]] practice echo " Welcome ${NUMBER} times " (( NUMBER++ )) done
This is a very simple example, where the loop executes until NUMBER is not greater than 10 and prints the echo statement.
Forth with while nosotros will use the read command to read the contents of a file line past line. Below is the syntax of how while and read commands are combined. Now at that place are unlike ways to laissez passer the file as input and nosotros will see them all.
# SYNTAX while read VARIABLE do code done
Piping in Linux
Commonly we will use the cat command to view the contents of the file from the concluding. Also, we volition pipe the output of the cat command to other commands like grep, sort, etc.
Similarly, we will apply the true cat command here to read the content of the file and pipe it to a while loop. For demonstration, I am using /etc/passwd file just information technology is not advisable to mess with this file so accept a backup copy of this file and play with it if you desire then.
cat /etc/passwd | while read LREAD do echo ${LREAD} done
Let'south suspension down what will happen when the above code is submitted.
- true cat /etc/passwd will read the contents of the file and laissez passer it as input through the pipage.
- read control reads each line passed as input from cat command and stores it in the LREAD variable.
- read command will read file contents until EOL is interpreted.
You lot can also apply other commands like head, tail, and piping it to while loop.
caput -n 5 /etc/passwd | while read LREAD do echo ${LREAD} washed
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
You tin can also store the file proper noun to a variable and laissez passer it through a redirection operator.
FILENAME="/etc/passwd" while read LREAD practice repeat ${LREAD} done < ${FILENAME}
You can also pass file names as an argument to your script.
while read LREAD do repeat ${LREAD} done < $1 | head -n five
Internal Field Separator
Y'all may piece of work with different types of file formats (CSV, TXT, JSON) and you may desire to dissever the contents of the file based on a custom delimiter. In this case, you can use "Internal field separator (IFS)" to split the content of the file and store it in variables.
Let me demonstrate how it works. Accept a look at the /etc/passwd file which has a colon (:)
as the delimiter. You can at present separate each give-and-take from a line and store it in a separate variable.
In the below example, I am splitting /etc/passwd file with a colon every bit my separator and storing each carve up into dissimilar variables.
while IFS=":" read A B C D E F K practice repeat ${A} echo ${B} echo ${C} echo ${D} echo ${E} echo ${F} echo ${G} done < /etc/passwd
I displayed just ane line split up in the above screenshot considering screenshot size.
Empty Lines in Linux
Empty lines are non ignored when you loop through the file content. To demonstrate this I have 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 two, and some escape characters (\due north and \t).
while read LREAD do echo ${LREAD} done < testfile
Come across the result, blank line is not ignored. Also, an interesting thing to note is how white spaces are trimmed by the read control. A unproblematic way to ignore blank lines when reading the file content is to apply the exam operator with the -z
flag which checks if the string length is zilch. At present permit's echo the same example merely this time with a test operator.
while read LREAD practise if [[ ! -z $LREAD ]] and so echo ${LREAD} fi done < testfile
Now from the output, you can see empty lines are ignored.
Escape Characters
Escape characters like \n
, \t
, \c
volition non be printed when reading a file. To demonstrate this I am using the same sample file which has few escape characters.
while read LREAD do echo ${LREAD} done < testfile
You tin encounter from the output escape characters take lost their meaning and only north and t are printed instead of \northward
and \t
. Yous can use -r
to prevent backslash interpretation.
while read -r LREAD exercise echo ${LREAD} done < testfile
That's information technology for this article. We would love to hear back from you if at that place are whatever feedbacks or tips. Your feedback is what helps us to create better content. Keep reading and go along supporting.
If You Appreciate What We Do Hither On TecMint, You Should Consider:
TecMint is the fastest growing and almost trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or scan the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending back up.
Source: https://www.tecmint.com/different-ways-to-read-file-in-bash-script/
0 Response to "Bash Read File Line 3 to Variable"
Post a Comment