1

I am in need of converting the below in multiple files. Text need not be same, but will be in the same format and length

File 1:

XXXxx81511
XXX is Present
abcdefg
07/09/2014
YES
1
XXX
XXX-XXXX

File 2:

XXXxx81511
XXX is Present
abcdefg
07/09/2014
YES
1
XXX
XXX-XXXX

TO

XXXxx81511,XXX is Present,abcdefg,07/09/2014,YES,1,XXXXXX-XXXX

XXXxx81511,XXX is Present,abcdefg,07/09/2014,YES,1,XXXXXX-XXXX

Basically converting row to column and appending to a new file while adding commas to separate them.

I am trying cat filename | tr '\n' ',' but the results do get added in the same line. like this

XXXxx81511,XXX is Present,abcdefg,07/09/2014,YES,1,XXXXXX-XXXX,XXXxx81511,XXX is Present,abcdefg,07/09/2014,YES,1,XXXXXX-XXXX

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
user1659329
  • 75
  • 1
  • 7

4 Answers4

4

Use:

paste -sd, file1 file2 .... fileN
#e.g.
paste -sd, *.txt file*

prints

XXXxx81511,XXX is Present,abcdefg,07/09/2014,YES,1,XXX,XXX-XXXX
XXXxx81511,XXX is Present,abcdefg,07/09/2014,YES,1,XXX,XXX-XXXX

and if you need the empty line after each one

paste -sd, file* | sed G

prints

XXXxx81511,XXX is Present,abcdefg,07/09/2014,YES,1,XXX,XXX-XXXX

XXXxx81511,XXX is Present,abcdefg,07/09/2014,YES,1,XXX,XXX-XXXX

Short perl variant:

perl -pe 'eof||s|$/|,|' files....
clt60
  • 62,119
  • 17
  • 107
  • 194
1

You need to insert an echo after tr. Use a script like this:

for f in file1 file2; do
    tr '\n' ',' < "$f"; echo
done > files.output
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Use a for loop:

for f in file*; do sed ':a;N;$!ba;s/\n/,/g' < $f; done

The sed code was taken from sed: How can I replace a newline (\n)?. tr '\n' ',' didn't work on my limited test setup.

Community
  • 1
  • 1
Burkart
  • 462
  • 4
  • 9
0
perl -ne 'chomp; print $_ . (($. % 8) ? "," : "\n")' f*

where:

  • -n reads the file line by line but doesn't print each line
  • -e executes the code from the command line
  • 8 number of lines in each file
  • f* glob for files (replace with something that will select all your files). If you need a specific order, you will probably need something more complicated here.
Sorin
  • 5,201
  • 2
  • 18
  • 45