Search code examples
bashunixappendline

append filename to each line


I need to add the filename at the end of each line.. this is how I do it..

 files=($(ls | grep -i -E 'XYZ_')) 

 length=${#files[*]}
 for ((i=0;i<=$(($length - 1)); i++)) 
 do
    sed "s/$/$(basename ${files[$i]}) /g" ${files[$i]} >> output
 done

The problem is the result..

here's a line 20170302105D AAA.AAAE AR 1111 HHH1,0PPP

here's how it could be

20170302105D AAA.AAAE AR 1111 HHH1,0PPPXYZ_FILENAME

or

20170302105D AAA.AAAE AR 1111 HHH1,0PPP XYZ_FILENAME

Here's instead the result

20170302105D AAA.AAAE AR 1111 HHH1,0PPP

XYZ_FILENAME

20160307205D bbb.bbbE AR 12511 HHH1,0PPP

XYZ_FILENAME

So it appends the filename as a new line.. How can I solve it?

Thank you


Solution

  • It turned out that Windows line endings were causing the issues.


    Anyhow I recommend to use this single awk command for that.

    awk '{print $0, FILENAME}' *XYZ_*
    

    (that's all, no shell loop)