Grep ignoring/not 捕获文件的第一行

Grep ignoring/not catching first line of file

我正在尝试编写一个脚本来读取文件的所有行,并在 grep 中包含 expecify 词的情况下对一行进行 grep(在本例中该词是 apple),但我遇到的问题是 grep正在 ignoring/not 捕获文件的第一行。

这是我的脚本:

#!/bin/bash

while read line;
do
    grep 'apple' > fruits2.txt
    
done < fruits.txt

输入文件“fruits.txt”

apple 1
banana
apple 2
grape
orange
apple 3
blueberry
apple 4

输出文件“fruits2.txt”

apple 2
apple 3
apple 4

所以你正在创建一个循环,以便逐行读取整个文件,并让 grep 验证该行中是否有内容。

你说得对 grep 只能读一行。

但是:grep 可以读取整个文件,这就是创建的目的。

所以,您不需要创建自己的循环,您可以这样做:

grep "apple" fruits.txt

结果将是:

apple 1
apple 2
apple 3
apple 4

另外:假设您将“pineapple 666”添加到“fruits.txt”文件中,那么您也会在输出中看到这个。如果您不想这样:

grep -w "apple" fruits.txt

-w 表示只能显示整个单词。)