11

The file letters.csv contains:

b,a,c,

The file numbers.csv contains:

32
34
25
13

I would like to append numbers.csv to letters.csv like this:

b,a,c,32,34,25,13

I have tried this:

sed -e :a -e '{N; s/\n/,/g; ta}' numbers.csv >> letters.csv

However, this puts the appended entries on a new line:

b,a,c,
32,34,25,13

I would like all entries on the same line. How can this be done?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
IslandPatrol
  • 261
  • 3
  • 11
  • The append output redirect (`>>`) appends to wherever the end of the file is. If there's a newline there, appended data comes after that. If there's no trailing newline, appended bytes appear on the same line. – KingRadical Nov 05 '16 at 02:16
  • If I were you I'd append some letters to the numbers line, as well. – Jack Maddington Nov 05 '16 at 10:08

4 Answers4

7

You can do it with paste alone.

First, convert contents in numbers.csv to comma-separated values. -s is the serial option and -d, specifies comma as delimiter:

$ paste -sd, numbers.csv
32,34,25,13

Then append this output to letters.csv by specifying an empty delimiter and process substitution:

$ # use -d'\0' for non-GNU version of paste
$ paste -d '' letters.csv <(paste -sd, numbers.csv) > tmp && mv tmp letters.csv
$ cat letters.csv
b,a,c,32,34,25,13


To modify sed command posted in OP, use command substitution:

$ sed -i -e "s/$/$(sed -e :a -e '{N; s/\n/,/g; ta}' numbers.csv)/" letters.csv
$ cat letters.csv
b,a,c,32,34,25,13
Sundeep
  • 23,246
  • 2
  • 28
  • 103
5

You can use tr:

cat letters.csv numbers.csv | tr '\n' ',' | sed 's/,$/\n/'

(I hope this is not a useless use of cat. :-))

The sed at the end is needed to replace the last , with a newline character.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pfnuesel
  • 14,093
  • 14
  • 58
  • 71
3

awk to the rescue!

$ awk 'NR==FNR{printf "%s",$0; next} 
              {print $0} 
           END{ORS="\n"; print ""}' letters ORS=, numbers | 
  sed '$s/,$//'    # to delete last ","

b,a,c,32,34,25,13
karakfa
  • 66,216
  • 7
  • 41
  • 56
2
awk 'FNR==NR{t=$0;next}{s=s","$0}END{print t s}' letters.csv numbers.csv 
zxy
  • 148
  • 1
  • 2
  • this is good alternate with awk, however it doesn't handle trailing `,` in letters.csv.. which is easy to fix with `awk 'FNR==NR{t=$0;next}{s=FNR==1?$0:s","$0}END{print t s}' letters.csv numbers.csv` – Sundeep Nov 05 '16 at 08:24