如何将新行字符转换为制表符,然后在bash循环中插入换行符

时间:2016-08-16 14:59:37

标签: bash for-loop

我的输入目录中有一些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 

由于

3 个答案:

答案 0 :(得分:1)

如果每个文件的输出肯定包含文件名和数字,我认为您可以轻松更改

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

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

它将匹配选项卡后跟的数字,然后添加新的换行符。

答案 1 :(得分:1)

您可以通过将所有内容写入一行来获得所需的输出。类似的东西:

function insert($anchor, &$stuff)

如果您想分两部分进行,请注意echo -e "$file\t$(samtools view -F 4 $file | wc -l)" >> output; 有一个echo选项可以禁止尾随换行符,-n可以解释-e之类的转义符,所以你可以这样做:

\t

第一次写下你想要的东西比试图对你的输出进行后期处理更清晰。

答案 2 :(得分:1)

只需使用命令替换:

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