代码之家  ›  专栏  ›  技术社区  ›  drmaa

为什么cat命令不在脚本中工作

  •  -3
  • drmaa  · 技术社区  · 8 年前

    我有下面的脚本,它有一个错误。我正在尝试将所有文件合并到一个大文件中。从命令行,cat commant工作正常,内容被打印到重定向文件。从脚本来看,它有时会工作,但不是在另一时间。我不知道为什么它的行为异常。请帮忙。

    #!/bin/bash
    
    ### For loop starts ###
    
    for D in `find . -type d`
    do
    
            combo=`find $D -maxdepth 1 -type f -name "combo.txt"`
            cat $combo >> bigcombo.tsv
    
    done
    

    这是的输出 bash -x app.sh

    ++ find . -type d
    + for D in '`find . -type d`'
    ++ find . -maxdepth 1 -type f -name combo.txt
    + combo=
    + cat
    ^C
    

    更新:

    #!/bin/bash
    
    ### For loop starts ###
    rm -rf bigcombo.tsv
    
    for D in `find . -type d`
    do
    
                    psi=`find $D -maxdepth 1 -type f -name "*.psi_filtered"`
                    # This will give us only the directory path from find result i.e. removing filename.
                    directory=$(dirname "${psi}")
                    cat $directory"/selectedcombo.txt" >> bigcombo.tsv
    
    
    done
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   tripleee    8 年前

    明显的问题是你试图 cat 不存在的文件。

    次要问题与效率和正确性有关。最好避免运行两个嵌套循环,尽管在这里将操作拆分为两个步骤仅仅是不雅的;内部循环最多只执行一次。将命令结果捕获到变量中是一个常见的初学者反模式;通常可以避免只使用一次的变量,并避免将shell内存中的cruft乱扔(并且巧合地解决了缺少引号的多个问题-包含文件或目录名的变量基本上应该始终插入双引号)。重定向最好在任何包含循环之外执行;

    rm file
    while something; do
        another thing >>file
    done
    

    将打开、查找文件的结尾、写入和关闭文件的次数与循环运行的次数相同,而

    while something; do
        another thing
    done >file
    

    只执行一次“打开”、“查找”和“关闭”操作,并避免在开始循环之前清除文件。尽管您的脚本可以重构为完全没有任何循环;

    find ./*/ -type f -name "*.psi_filtered" -execdir cat selectedcombo.txt \;> bigcombo.tsv
    

    根据您的问题,可能存在包含 combo.txt 但里面没有 *.psi_filtered 文件夹。也许你想 locate and examine these directories.