【问题标题】:Cat one file onto same named file in another directory将一个文件添加到另一个目录中的同名文件中
【发布时间】:2016-11-09 23:39:37
【问题描述】:

我正在尝试将 *.txt 的内容放到另一个目录中的另一个同名文件中。例如。 ../../*.txt

我试过了:

find . -type f -name "*.txt" -exec cat {} \; >> ../../*.txt

还有一些变化,但最终会出现一个模棱两可的重定向错误或什么都没有。

我在这里错过了什么?

【问题讨论】:

    标签: bash unix find cat


    【解决方案1】:

    对于 1 个文件:

    cat ./file1.txt >> ../../file1.txt
    

    您的问题建议使用 1 个文件,但您的 find 命令建议使用 *.txt 类型的许多文件

    要执行*.txt 类型的多个文件并根据您的find 命令尝试:

    find . -name "*.txt" -print0 | while read -d $'\0' filename
    do
      cat ./$filename >> ../../$filename
    done
    

    【讨论】:

      【解决方案2】:

      * 不进行一对一映射。它将被 bash 扩展以表示 ../../ 目录中的所有 txt 文件。这导致了错误,因为现在您正尝试重定向到多个文件。

      使用 for 循环而不是 find 可能更容易做到这一点,因为您需要引用文件名两次。

      for file in *.txt
      do
          if [ -f ./$file ] ; then 
              cat ./$file >> ../../$file
          fi
      done
      

      【讨论】:

        【解决方案3】:

        将 *.txt 的内容放到另一个同名文件中

        本质上,您是在此处复制文件。你不是吗?

        所以下面的东西应该适合你。

        find . -type f -iname "*.txt" -exec cp bash -c 'cp "$1" ../../"$1"' _ {} \;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-03-12
          • 2017-12-11
          • 1970-01-01
          • 2018-10-13
          • 1970-01-01
          • 2021-09-02
          • 1970-01-01
          • 2018-03-13
          相关资源
          最近更新 更多