Issue
I am trying to do a script that read all lines of a file and grep a line if contains the expecify word in the grep (in this case the word is apple), but I am having a issue that the grep is ignoring/not catching the first line of the file.
Here is my script:
#!/bin/bash
while read line;
do
grep 'apple' > fruits2.txt
done < fruits.txt
The input file "fruits.txt"
apple 1
banana
apple 2
grape
orange
apple 3
blueberry
apple 4
The output file "fruits2.txt"
apple 2
apple 3
apple 4
Solution
So you are creating a loop, in order to read an entire file line by line, and let grep
verify if there is something inside that line.
You are correct that grep
can read just a single line.
But: grep
can read an entire file, that's what is has been created for.
So, you don't need to create your own loop, you can just do:
grep "apple" fruits.txt
The result will be:
apple 1
apple 2
apple 3
apple 4
As an extra: imagine that you add "pineapple 666" to your "fruits.txt" file, then you will see this one too in your output. In case you don't want that:
grep -w "apple" fruits.txt
(the -w
says that only entire words may be shown.)
Answered By - Dominique Answer Checked By - Cary Denson (WPSolving Admin)