【问题标题】:Grep ignoring/not catching first line of fileGrep忽略/不捕获文件的第一行
【发布时间】:2021-06-11 13:45:47
【问题描述】:

我正在尝试编写一个脚本来读取文件的所有行,如果在 grep 中包含 expecify 单词(在本例中为 apple),则 grep 一行,但我遇到了 grep 忽略的问题/没有捕捉到文件的第一行。

这是我的脚本:

#!/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

【问题讨论】:

  • read line 读取第一行,grep 甚至看不到它。
  • 只需使用grep 'apple' fruits.txt &gt; fruits2.txt,无需循环。
  • 请将该示例输入的所需输出(无描述、无图像、无链接)添加到您的问题(无评论)。

标签: linux bash shell grep


【解决方案1】:

所以你正在创建一个循环,以便逐行读取整个文件,并让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 表示只能显示整个单词。)

【讨论】:

    猜你喜欢
    • 2010-12-02
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    相关资源
    最近更新 更多