Monday 12 August 2019

Bash: Use for loop to iterate over file without using cat

Introduction:

In this very brief post I just wanted to demonstrate a way to use the for loop to iterate over a file without using the cat command.

Here is a file containing 10 numbers, 1 number on each line.

cat seq.txt
1
2
3
4
5
6
7
8
9
10

If I wanted to loop over it using for loop in bash I could type:

for i in `cat seq.txt`; do echo $i ;done

But what if I don't want to read in the file using cat command?
I could use input redirection to read in the file contents as shown in the below example:

for i in $(<seq.txt); do echo $i ; done
1
2
3
4
5
6
7
8
9
10
                            
One more way of avoiding the cat command would be to read the file into an array and then loop over the array as shown below.

readarray -t ARR < seq.txt

for i in "${ARR[@]}"; do echo $i; done
1
2
3
4
5
6
7
8
9
10


Conclusion

There is nothing wrong with using the cat command to read in file contents while iterating over it in a for loop. I just found redirecting directly from STDIN to be more elegant and I would try to use it more often.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...