Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a file using a bash script

Tags:

bash

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' 
like image 670
Leonardo Avatar asked Feb 20 '11 12:02

Leonardo


People also ask

How do I read a file in bash?

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.

How do I open a text file in shell script?

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.

How do I read a file in Linux?

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.

How do I process a file line by line in bash?

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.


2 Answers

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).

like image 76
Adam Liss Avatar answered Nov 10 '22 20:11

Adam Liss


cat file | while read line do   echo "a line: $line" done 

EDIT:

To get file contents into a var use:

foo="`cat file`" 
like image 24
Erik Avatar answered Nov 10 '22 21:11

Erik