【问题标题】:Bash Script How to find every file in folder and run command on itBash脚本如何找到文件夹中的每个文件并在其上运行命令
【发布时间】:2018-09-15 01:43:30
【问题描述】:

所以我试图创建一个在文件夹中查找并找到所有具有 .cpp 的文件类型并在其上运行 g++ 的脚本。到目前为止我有但它没有运行它说意外结束

for i in `find /home/Phil/Programs/Compile -name *.cpp` ; do echo $i ; 
done

谢谢

【问题讨论】:

  • 你使用的是什么外壳,在哪个操作系统上?

标签: bash


【解决方案1】:

您的代码的问题是通配符* 在传递给查找之前被shell 扩展。如此引用它:

for i in `find /home/Phil/Programs/Compile -name '*.cpp'` ; do echo $i ;  done

不过,其他人建议的xargs 是解决此问题的好方法。

【讨论】:

    【解决方案2】:

    find 可以选择这样做:

    find /p/a/t/h -name '*.cpp' -exec g++ {} \;
    

    【讨论】:

      【解决方案3】:

      此代码适用于我:

      #!/bin/bash
      
      for i in `find /home/administrator/Desktop/testfolder -name *.cpp` ; do echo $i ; 
      done
      

      我明白了:

      administrator@Netvista:~$ /home/administrator/Desktop/test.sh
      /home/administrator/Desktop/testfolder/main.cpp
      /home/administrator/Desktop/testfolder/main2.cpp
      

      【讨论】:

      • ./bashscript.sh:第 2 行:$'\r':找不到命令 ./bashscript.sh:第 18 行:语法错误:文件意外结束
      • 你的文件名是什么?
      • @user2872510 你在cygwin上吗?脚本中可能的 Windows \r\n 换行符?
      • 您的代码可以正常工作,因为您很幸运/很不幸,您的主目录中没有任何 *.cpp 文件,因此 *.cpp 被顺利通过以找到。
      • 哦。我知道这是一些通配符。
      【解决方案4】:

      你可以像这样使用 xargs:

      find folder/ -name "*.cpp" | xargs g++

      或者如果你想处理包含空格的文件:

      find folder/ -name "*.cpp" -print0 | xargs -0 g++

      【讨论】:

        【解决方案5】:

        我想你想用xargs:

        例如:

        find /home/Phil/Programs/Compile -name *.cpp | xargs g++
        

        【讨论】:

        • 你是不是要查找两次
        • 不,这是 Bryan 的错字。
        【解决方案6】:

        像这样使用 xargs 怎么样:

        find $working_dir -type f -name *.cpp | xargs -n 1 g++
        

        【讨论】:

          猜你喜欢
          • 2018-05-17
          • 2014-06-11
          • 2020-08-27
          • 2011-11-13
          • 2011-09-22
          • 1970-01-01
          • 2017-03-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多