File Read and Write

I have got a file in following format:

AAAAAAA
BBBBBBBB
CCCCCCC
DDDDDDD

I am trying to read this file and out put it in following format:

AAAAAAA,BBBBBBB,CCCCCCC,DDDDDD

Preferred method is shell or Perl.

Any help appreciated.

paste -sd, file

OR

tr '\n' ',' < file
1 Like

I have got it working but have to change slightly:

I have got a file in following format:

AAAAAAA
BBBBBBBB
CCCCCCC
DDDDDDD

I am trying to read this file and out put it in following format:

'AAAAAAA','BBBBBBB','CCCCCCC',DDDDDD'

Preferred method is shell or Perl.

Any help appreciated.

I have got a file in following format:

AAAAAAA
BBBBBBBB
CCCCCCC
DDDDDDD

I am trying to read this file and out put it in following format:

'AAAAAAA','BBBBBBB','CCCCCCC',DDDDDD'

Any help appreciated.

With a shell which supports process substitution:

paste -sd, <(sed 's/^/'"'"'/;s/$/'"'"'/' file)

or

sed 's/^/'"'"'/;s/$/'"'"'/' file|paste -sd, -

or with only sed (will hog some memory though, depending on the file size):

sed -n 's/.*/'"'"'&'"'"'/;H
${;g;s/^\n//;s/\n/,/g;p;}' file

OR..

sed "s/.*/\'&\'/" file | tr '\n' ','

And removing the unnecessary backslashes from pamu's solution:

sed "s/.*/'&'/" file|tr '\n' ','

@pamu, do you realize that your solution with tr will end up eating the last new-line? This might not be desired.

sed "s/.*/'&'/" yourfile | paste -sd, -
# cat myt
AAAAAAA
BBBBBBBB
CCCCCCC
DDDDDDD
# sed "s/.*/'&'/" myt | paste -sd, -
'AAAAAAA','BBBBBBBB','CCCCCCC','DDDDDDD'

Thread was merged because there was a double thread...

1 Like

Ah Oooops, yeah... Thx Scruti :smiley:

By definition, all lines in a text file must be newline terminated. Given a proper text file, tr's output will include an unwanted, trailing comma. Further, that output itself will not be a valid text file (even if it is just one "line").

Regards,
Alister

EDIT: I just noticed that elixir touched upon this earlier.