【问题标题】:How to convert the new line character to tab and then insert new line character in a loop in bash如何将换行符转换为制表符,然后在bash的循环中插入换行符
【发布时间】:2016-08-16 14:59:36
【问题描述】:

我的输入目录中有一些bam 文件,对于每个bam 文件,我想计算映射读取的数量(使用Samtools view 命令)并打印该数字以及bam 的名称文件转换为输出文件。虽然它正在工作,但我没有得到我想要的输出。

这是我的代码的样子

for file in input/*;
        do
        echo $file >> test.out;
        samtools view -F 4 $file | wc -l >> output;
        done

这很好用,但问题是它会在不同的行中输出文件名和读取次数。这是一个例子

sample_data/wgEncodeUwRepliSeqBg02esG1bAlnRep1.bam
1784867
sample_data/wgEncodeUwRepliSeqBg02esG2AlnRep1.bam
2280544

我试图通过这样做将换行符转换为制表符

for file in input/*;
            do
            echo $file >> output;
            samtools view -F 4 $file | wc -l >> output;
            tr '\n' '\t' < output > output2
            done

这是相同的输出

sample_data/wgEncodeUwRepliSeqBg02esG1bAlnRep1.bam      1784867 sample_data/wgEncodeUwRepliSeqBg02esG2AlnRep1.bam       2280544 

现在如何在每行之后插入换行符?例如

sample_data/wgEncodeUwRepliSeqBg02esG1bAlnRep1.bam      1784867     
sample_data/wgEncodeUwRepliSeqBg02esG2AlnRep1.bam       2280544 

谢谢

【问题讨论】:

  • 为什么不建生产线? echo -e "$file\t$var",其中$var 包含samtools view... 的输出。

标签: bash for-loop


【解决方案1】:

您可以通过将所有内容写在一行中来获得所需的输出。比如:

echo -e "$file\t$(samtools view -F 4 $file | wc -l)" >> output;

如果你想分成两部分,请注意echo 有一个-n 选项来抑制尾随换行,-e 可以解释像\t 这样的转义,所以你可以这样做:

echo -ne "$file\t" >> $output
samtools view -F 4 $file | wc -l >> output

第一次写出你想要的东西比尝试后处理你的输出更干净。

【讨论】:

    【解决方案2】:

    如果每个文件的输出肯定由文件名和数字组成,我想你可以很容易地改变

    tr '\n' '\t' < output > output2
    

    tr '\n' '\t' < output | sed -r 's/([0-9]+\t)/\1\n/' > output2
    

    它将匹配数字后跟一个制表符,然后添加一个换行符。

    【讨论】:

    • 工作得很好。是的,所有文件的输出都是相同的。我怎么会忘记sed 的力量。顺便问一下\1 在那里做什么?是为了捕获类似于R 的组吗?谢谢..
    • 是的,\1 指的是第一个匹配的组件,即 ([0-9]+\t) 用括号括起来。 :-)
    【解决方案3】:

    只需使用命令替换:

    for file in input/*
    do
        printf '%s\t%d\n' "$file" "$(samtools view -F 4 $file | wc -l)"
    done >> output
    

    【讨论】:

      猜你喜欢
      • 2011-02-06
      • 2015-06-21
      • 2013-06-26
      • 1970-01-01
      • 2013-09-10
      • 2021-06-14
      相关资源
      最近更新 更多