Search code examples
bashcut

How to save the cut command result in a file


my question is simple:

I used :

for file in `/path/*_aa.fasta.aln; do cut -f 1 -d "|" ${file} > ${file}.1; done`

Here as you can see I store the result in the ${file}.1 but how to juste do it on ${file} directly ?


Solution

  • As you can't read and write to a file sumltanously, you need to save/buffer the output, then output (the output) to the file.

    Example like (this removes/adds only one trailing empty newlines):

    cmd file | { buf=$(cat); printf "%s\n" "$buf" } > file
    

    or:

    temp=$(mktemp)
    cmd file > "$temp"
    mv "$temp" file
    

    or if you have sponge which does exactly that:

    cmd file | sponge file
    

    So you can:

    for file in /path/*_aa.fasta.aln; do 
        cut -f 1 -d "|" ${file} > ${file}.1
        mv ${file}.1 ${file}
    done
    

    or if you have sponge:

    for file in /path/*_aa.fasta.aln; do 
        cut -f 1 -d "|" "${file}" | sponge "${file}"
    done
    

    Note: don't use backquotes ` `. Use command substitution $( ... ). Backquotes are deprecated, unreadable and become more unreadable when nested.