0

I am stuck with it not getting how to proceed with it

I have a folder called : demo

In that their are n number of files , but files will have only one column data and that to vertical form

Need to convert that vertical data like below to horizontal comma separated form without creating new file using sed

Data in file 1 :

ABX
aHA
AHAK
AFGJK
AA

Data in file 2 :

1234
hakk
1567
gahsll

using sed command both file data should be converted to horizontal comma separated format

My command :

sed -i 's/\n//g' /Demo/*.*

Output :

ABX,aHA,AHAK,AFGJK,AA

Similarly for file 2 as well

Note : Demo folder can contain n number of files

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Please clarify whether the comma separated rows from *file1* and *file2* should be output to one file containing many lines of such rows, or separate files each containing one row. (If the latter, then the "multiple file" requirement in the title seems irrelevant.) – agc Oct 28 '21 at 16:19

1 Answers1

2

This might work for you (GNU paste):

paste -sd, file > tempFile && mv tempFile file

The -s pastes serially and the -d is the separator.

or use sed:

sed -zi 's/\n/,/g;s/,$/\n/' file

The -z option slurps the whole file into the pattern space.

The -i option allows editing inplace.

Substitute all newlines by ,'s and restore the last newline if the file ends in a newline.

Alternative:

sed -i 'H;$!d;x;s/.//;s/\n/,/g' file

Copy the whole of the file into the hold space, remove the first newline and then replace all other newlines by ,'s.

potong
  • 55,640
  • 6
  • 51
  • 83
  • I need to overide th data into same file does it does –  Oct 28 '21 at 15:41
  • @wovef57249 direct output to a temp file and the mv the temp to the original e.g `paste -sd, file > temp && mv temp file` – potong Oct 28 '21 at 15:44
  • Or, install `moreutils` and do `paste -sd, file | sponge file` – glenn jackman Oct 28 '21 at 15:45
  • @glennjackman : can it be possible using sed command using inplace option `ì` -> sed i ... can you share –  Oct 28 '21 at 15:47
  • @potong : can you explain the sed command step by step what is happening –  Oct 28 '21 at 15:55
  • In my opinion, the extreme terseness of sed far overrides the usefulness of `-i`. @wovef57249, see https://www.gnu.org/software/sed/manual/html_node/index.html (particularly [3.5 Less Frequently-Used Commands](https://www.gnu.org/software/sed/manual/html_node/Other-Commands.html#Other-Commands)) for the meaning of those sed commands. – glenn jackman Oct 28 '21 at 19:19