【问题标题】:grep the lines of file using for loop使用 for 循环 grep 文件行
【发布时间】:2021-02-05 01:52:51
【问题描述】:

有一个文件,每一行显示不同的文件路径。

    ```
      my_file
      /the/first/path/file1
      /the/second/path/file2
      ....
    ```

我想使用 for 循环在每个文件中查找一个字符串。

     ```
      for i in $(cat my_file); do cd "$i"; done | grep -w string "$i"

     ```

但这似乎对我不起作用。我正在为所有文件目录获取这个

    -bash: cd: /the/first/path/file1: No such file or directory

我做错了什么?在此先感谢您的帮助

【问题讨论】:

    标签: linux bash for-loop grep cd


    【解决方案1】:

    不需要for 循环,使用xargs

    xargs -a my_file -d '\n' grep -h -w string
    

    注意 #1:我添加了 -h 选项(GNU 扩展名),因此grep 不会在输出中添加文件名(就像在您的命令中一样)。

    注意 #2:由于您使用的是 Linux 和 Bash,我假设 GNU xargs。如果您的 xargs 不理解 -a 选项,请改用此选项:

    < my_file xargs -d '\n' grep -h -w string
    

    【讨论】:

    • 谢谢,但仍然有同样的问题“grep: /the/first/path/file1: No such file or directory”。当我尝试单独搜索它时: 它可以工作。奇怪,不知道怎么回事
    • 该文件不存在,对此我无能为力。如果文件存在,您会看到我的命令有效,而不是您的。
    • 您的有效示例使用 ~/the/first/path/file1。您的示例未使用 /the/first/path/file1。 ~ 表示你的主目录。 / 表示文件系统的根目录。完全不同的东西。
    • 好收获@NicholasRees!
    猜你喜欢
    • 2015-03-24
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 2015-08-17
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多