合并具有相同名称但不同代码的文件 – UNIX

huangapple go评论59阅读模式
英文:

Merge files with the same name but different code - UNIX

问题

我想要合并具有相同部分的文件:

XX_barcode2_XX.fastq
XX_barcode2_XX.fastq
XX_barcode3_XX.fastq
XX_barcode3_XX.fastq
XX_barcode4_XX.fastq
XX_barcode4_XX.fastq

所以,我想要一个用于barcode2的文件,一个用于barcode3等等...

我尝试了这个:

for i in {2 .. 96};
do
   cat *_barcode$i*.fastq >> barcode$i.fastq;
done

但它不起作用。有什么想法?

英文:

I would like to merge files which have the same part of the same:

XX_barcode2_XX.fastq
XX_barcode2_XX.fastq
XX_barcode3_XX.fastq
XX_barcode3_XX.fastq
XX_barcode4_XX.fastq
XX_barcode4_XX.fastq

So, I would like a file for barcode2, a file for barcode3 etc...

I was trying this:

for i in {2 .. 96};
do
   cat *_barcode$i*.fastq >> barcode$i.fastq;
done

but it does not work. Any ideas?

答案1

得分: 1

我会这样做:

#!/bin/bash

echo "file2 A" > XX_barcode2_XX.fastq
echo "file2 B" > XX_barcode2_YY.fastq
echo "file3 A" > XX_barcode3_XX.fastq
echo "file3 B" > XX_barcode3_YY.fastq
echo "file4 A" > XX_barcode4_XX.fastq
echo "file4 B" > XX_barcode4_YY.fastq

for i in {2..96}
do
    echo "i=$i"
    if find . -name "*_barcode$i*.fastq"
    then
        echo "in if"
        cat "*_barcode$i*.fastq" >> "barcode$i.fastq"
    fi
done
  • 脚本顶部只是为我创建文件以供测试。
  • if find ... 是为了仅处理存在的文件。否则,它会创建从5到96的空文件。如果不需要,可以删除它。
  • 如果不需要调试消息,可以删除echo语句。
  • for循环中,您在{2 .. 96}周围放了空格,bash对于空格放错地方非常挑剔。
  • 您可以在发布之前使用 https://www.shellcheck.net/ 验证您的语法。
  • 并且不需要使用;来结束行,这不是C语言 合并具有相同名称但不同代码的文件 – UNIX
英文:

I would do it like that:

#!/bin/bash

echo "file2 A" > XX_barcode2_XX.fastq
echo "file2 B" > XX_barcode2_YY.fastq
echo "file3 A" > XX_barcode3_XX.fastq
echo "file3 B" > XX_barcode3_YY.fastq
echo "file4 A" > XX_barcode4_XX.fastq
echo "file4 B" > XX_barcode4_YY.fastq

for i in {2..96}
do
    echo "i=$i"
    if find . -name "*_barcode$i*.fastq"
    then
        echo "in if"
        cat "*_barcode$i*.fastq" >> "barcode$i.fastq"
    fi
done
  • the top of the script it just to create files for me to test with.
  • the if find ... is to process only files that do exist. Otherwise, it creates empty files form 5 to 96. You can remove that if not required.
  • you can remove the echo statements if you do not need debug messages.
  • in your for loop, you had put spaces around the {2 .. 96}, bash is very particular about spaces in the wrong places.
  • you can validate your syntax using https://www.shellcheck.net/ before posting.
  • and ; are not required to end lines, this is not C 合并具有相同名称但不同代码的文件 – UNIX

huangapple
  • 本文由 发表于 2023年6月19日 23:41:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76508163.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定