1

For all the .fq files in the repaired_reads directory, I want to convert them to fasta format, where conversion for a single file can be done using:

sed -n '1~4s/^@/>/p;2~4p' INFILE.fq > OUTFILE.fasta

But when I write a for loop to create all the files, I get an error.

for f in `ls -1 ./repaired_reads/*.fq | sed 's/_.fq//'`;
do sed -n '1~4s/^@/>/p;2~4p' $f\.fq > ../fasta/$f\.fasta; # Convert fastq to fasta
done 

Traceback:

bash: ../fasta/./repaired_reads/SRR9200813_1.fq.fasta: No such file or directory
bash: ../fasta/./repaired_reads/SRR9200813_2.fq.fasta: No such file or directory
bash: ../fasta/./repaired_reads/SRR9200814_1.fq.fasta: No such file or directory
melolili
  • 1,237
  • 6
  • 16
  • 2
    [Why not parse ls output](https://unix.stackexchange.com/questions/128985/why-not-parse-ls) – Barmar Apr 06 '23 at 04:04
  • What's wrong with `for f in ./repaired_reads/*.fq`? You can use bash's built-in parameter expansion operators to remove the `_.fq` suffix. – Barmar Apr 06 '23 at 04:04
  • Why are you escaping the `.` characters in filenames? – Barmar Apr 06 '23 at 04:05
  • Do you have a `repaired_reads` subdirectory in `../fasta`? – Barmar Apr 06 '23 at 04:06
  • If not, you need to remove that from `$f` when creating the output filename. – Barmar Apr 06 '23 at 04:07
  • Is there really a `_` before `.fq` in the input filenames? Why are you removing that, but not adding it back when you specify the input file to `sed`? – Barmar Apr 06 '23 at 04:13
  • See my answer [here](https://stackoverflow.com/questions/20796200/how-to-loop-over-files-in-directory-and-change-path-and-add-suffix-to-filename/20796617#20796617) for an example of how to do this sort of filename manipulation. – Gordon Davisson Apr 06 '23 at 04:40

1 Answers1

1

You need to remove the repaired_reads directory from $f when using it in the output path.

for f in repaired_reads/*.fq; do
    f=${f/.fq/} # remove .fq suffix
    outf=${f#*/}.fasta # remove directory prefix
    sed -n '1~4s/^@/>/p;2~4p' "$f.fq" > "../fasta/$outf" # Convert fastq to fasta
done
Barmar
  • 741,623
  • 53
  • 500
  • 612