How can I change the first line of multiple files including the name of the file?

Viewed 145

I have many files in a folder named as:

ctg_1.fasta
lcd2_13.fasta 
..
etc (all of them are .fasta)

I want to change the first line of each them to include the following: >ctg_1, >lcd2_13. I mean, that each file has its own name as the first line.

I think the command sed would help me. I tried to execute this:

var=">ctg_1"
sed -i "1s/.*/$var/" ctg_1.fasta

And it works, but I would like to do it recursively and that each file includes its own name.

Do you have any idea about how can I achieve this?

3 Answers

Use find to get all the files recursively. Extract the filename without .fasta suffix from the variable with the filename, and use that in the sed command.

find . -type f -name '*.fasta' | while read -r f; do
    base=$(basename "$f" .fasta)
    sed -i "1s/.*/>$base/" "$f"
done

This might work for you (GNU sed & parallel):

parallel sed -i '1s/.*/>{}/' {} ::: *.fasta

The -i option results in the amended file being done in place and each file will have its own line numbers thus 1s/.*/>{}/' replaces the first line of each file by a >and the{}` is the file name obtained by the parallel command.

You can use GNU awk:

awk -i inplace 'FNR==1{a=FILENAME;sub(/\.[^.]+$/, "", a);print a}1' *.fasta

Details:

  • -i inplace - inplace replacement
  • FNR==1 - if the current line is the first
  • {a=FILENAME;sub(/\.[^.]+$/, "", a);print a} - assign the file name to a, remove the last dot and all text after it, and print the result
  • 1 - default print action.
Related