Bash Script Read Word From File Into Variable
This article is all about how to read files in bash scripts using a while loop. Reading a file is a common operation in programming. You should be familiar with different methods and which method is more than efficient to use. In bash, a unmarried task can be accomplished in many means but there is always an optimal manner to become 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 gear up of codes when the condition is true.
while [ CONDITION ] practice code cake washed
Let's break down while loop syntax.
- while loop should offset with a while keyword followed by a condition.
- A condition should be enclosed inside [ ] or [[ ]]. The status should always return true for the loop to exist executed.
- The actual block of code will be placed between do and done.
NUMBER=0 while [[ $NUMBER -le 10 ]] do echo " Welcome ${NUMBER} times " (( NUMBER++ )) washed
This is a very simple instance, where the loop executes until NUMBER is not greater than 10 and prints the echo argument.
Forth with while we volition use the read control to read the contents of a file line by line. Beneath is the syntax of how while and read commands are combined. At present there are different ways to laissez passer the file equally input and nosotros will see them all.
# SYNTAX while read VARIABLE do lawmaking done
Piping in Linux
Usually we will use the true cat command to view the contents of the file from the terminal. Also, we volition pipe the output of the cat command to other commands like grep, sort, etc.
Similarly, we volition use the true cat command here to read the content of the file and pipage information technology to a while loop. For demonstration, I am using /etc/passwd file simply it is not advisable to mess with this file so accept a backup re-create of this file and play with information technology if you lot desire so.
cat /etc/passwd | while read LREAD do echo ${LREAD} done
Let'south break down what will happen when the above code is submitted.
- cat /etc/passwd volition read the contents of the file and pass information technology every bit input through the pipe.
- read command reads each line passed as input from true cat command and stores it in the LREAD variable.
- read command will read file contents until EOL is interpreted.
You can also employ other commands similar head, tail, and pipe information technology to while loop.
caput -due north five /etc/passwd | while read LREAD do echo ${LREAD} done
Input Redirection in Linux
We can redirect the content of the file to while loop using the Input redirection operator (<)
.
while read LREAD do echo ${LREAD} washed < /etc/passwd | head -n 5
You can besides shop the file name to a variable and pass it through a redirection operator.
FILENAME="/etc/passwd" while read LREAD do echo ${LREAD} done < ${FILENAME}
You tin also laissez passer file names as an argument to your script.
while read LREAD do repeat ${LREAD} done < $1 | caput -due north 5
Internal Field Separator
Y'all may work with dissimilar types of file formats (CSV, TXT, JSON) and y'all may want to split the contents of the file based on a custom delimiter. In this instance, you tin can utilize "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 (:)
equally the delimiter. You can at present split each discussion from a line and shop it in a separate variable.
In the below case, I am splitting /etc/passwd file with a colon as my separator and storing each carve up into unlike variables.
while IFS=":" read A B C D Eastward F Grand exercise echo ${A} echo ${B} echo ${C} echo ${D} repeat ${E} echo ${F} echo ${M} washed < /etc/passwd
I displayed simply ane line carve up 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 have created a sample file with the beneath content. There are four lines and few empty lines, leading whitespace, trailing white space, tab characters in line ii, and some escape characters (\n and \t).
while read LREAD do echo ${LREAD} done < testfile
See the result, blank line is not ignored. Also, an interesting affair 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 use the test operator with the -z
flag which checks if the string length is nil. Now let'due south repeat the same example merely this time with a test operator.
while read LREAD do if [[ ! -z $LREAD ]] then echo ${LREAD} fi done < testfile
Now from the output, y'all tin can run across empty lines are ignored.
Escape Characters
Escape characters similar \n
, \t
, \c
will not be printed when reading a file. To demonstrate this I am using the aforementioned sample file which has few escape characters.
while read LREAD do repeat ${LREAD} washed < testfile
You can see from the output escape characters have lost their pregnant and just n and t are printed instead of \n
and \t
. Y'all tin apply -r
to prevent backslash interpretation.
while read -r LREAD do echo ${LREAD} washed < testfile
That's information technology for this article. We would love to hear back from you if there are any feedbacks or tips. Your feedback is what helps u.s.a. to create meliorate content. Proceed reading and keep supporting.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community 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 are reading, please consider buying u.s. a coffee ( or 2 ) every bit a token of appreciation.
We are thankful for your never ending back up.
wilkersontrablinever.blogspot.com
Source: https://www.tecmint.com/different-ways-to-read-file-in-bash-script/
Belum ada Komentar untuk "Bash Script Read Word From File Into Variable"
Posting Komentar