Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over each line in a file with Bash?

Given a text file with multiple lines, I would like to iterate over each line in a Bash script. I had attempted to use cut, but cut does not accept \n (newline) as a delimiter.

This is an example of the file I am working with:

one two  three  four 

Does anyone know how I can loop through each line of this text file in Bash?

like image 555
pedr0 Avatar asked Mar 06 '12 16:03

pedr0


People also ask

How do I loop through a line in bash?

Simply setting the IFS variable to a new line works for the output of a command but not when processing a variable that contains new lines. As you can see, echoing the variable or iterating over the cat command prints each of the lines one by one correctly.

How do I iterate through a file in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

How do I loop over a file?

Execute the following command to insert the file's name, followed by a newline, followed by the text Loops Rule! into each file: for FILE in *; do echo -e "$FILE\nLoops Rule\!" > $FILE; done.


1 Answers

I found myself in the same problem, this works for me:

cat file.cut | cut -d$'\n' -f1 

Or:

cut -d$'\n' -f1 file.cut 
like image 80
Ivan Avatar answered Sep 28 '22 06:09

Ivan