Cat all files and add a tag as the file name before a character

Viewed 609

Hello everyone I have seevral files such as

FILE1
>content
AGGAGAjg
GAUGAUGUG
AAG
FILE2
>Againontent
HDHDIHD
DHHDDHK
DH

and I would like to cat all those files into one unique using cat FILE* >> Unique_file

but also to add the name of the file just before the > in each file.

then the content of the Unique_file would be :

>FILE1_content
AGGAGAjg
GAUGAUGUG
AAG
>FILE2_Againontent
HDHDIHD
DHHDDHK
DH
5 Answers

Could you please try following. Written and tested in GNU `awk.

awk 'FNR==1{sub(/^>/,"&"FILENAME"_")} 1' file1 file2

Explanation: Checking condition FNR==1 which will be true for each file's first line. Then substituting starting > with > and current filename with adding a _ in current line. 1 will print all rest of the lines.

NOTE: You can pass multiple files to awk, its capable of reading multiple files by it.

for file in $(ls FILE*); do echo $file >> unique_file; cat $file >> unique_file; done

This will echo the file name and append it to the output file before appending the contents of the file itself.

Looping on each file and using sed:

for fil in *;
do 
 sed "1s/>/>$fil\_/" $fil >> Unique_file;   # On the first line of the file substitute ">" for ">" followed by the file name (fil) and "_"
done

I made a combination of:

cat /sharedpath/{unique1,unique2,unique3}/filename > newfile

and

tail -n +1 file1 file2

into this:

tail -n +1 /sharedpath/{folder1,folder2,...,folder_n}/file.extension | cat > /sharedpath/newfile

The result is a newfile that contains the content from each subfolder (unique1,unique2..) in the {} brackets, separated by subfolder name.

note unique1=folder1

In my case the file.extension has the same name in all subfolders.

$ grep . file*|sed -E 's/(^[^:]*):>/>\1_/; s/^[^:]*://'
>file1_content
AGGAGAjg
GAUGAUGUG
AAG
>file2_Againontent
HDHDIHD
DHHDDHK
DH
Related