I need to read a file using a "Do/While" loop.
How can I read the contents as a string?
Here's my code:
cat directory/scripts/tv2dbarray.txt | while read line do echo "a line: $line" done
Error:
test.sh: line 4: syntax error near unexpected token `done' test.sh: line 4: `done'
Syntax: Read file line by line on a Bash Unix & Linux shell The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line: while read -r line; do COMMAND; done < input. file. The -r option passed to read command prevents backslash escapes from being interpreted.
Use the command line to navigate to the Desktop, and then type cat myFile. txt . This will print the contents of the file to your command line. This is the same idea as using the GUI to double-click on the text file to see its contents.
Cat. The simplest way to view text files in Linux is the cat command. It displays the complete contents in the command line without using inputs to scroll through it. Here is an example of using the cat command to view the Linux version by displaying the contents of the /proc/version file.
In Bash, you can use a while loop on the command line to read each line of text from a file and do something with it. Our text file is called “data. txt.” It holds a list of the months of the year. The while loop reads a line from the file, and the execution flow of the little program passes to the body of the loop.
There's no reason to use cat
here -- it adds no functionality and spawns an unnecessary process.
while IFS= read -r line; do echo "a line: $line" done < file
To read the contents of a file into a variable, use
foo=$(<file)
(note that this trims trailing newlines).
cat file | while read line do echo "a line: $line" done
EDIT:
To get file contents into a var use:
foo="`cat file`"
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