10

I have the following line in a unix script:

head -1 $line | cut -c22-29  >> $file

I want to append this output with no newline, but rather separated with commas. Is there any way to feed the output of this command to printf? I have tried:

head -1 $line | cut -c22-29 | printf "%s, " >> $file

I have also tried:

printf "%s, " head -1 $line | cut -c22-29 >> $file

Neither of those has worked. Anyone have any ideas?

KateMak
  • 1,619
  • 6
  • 26
  • 42

2 Answers2

13

You just want tr in your case

tr '\n' ','

will replace all the newlines ('\n') with commas

head -1 $line | cut -c22-29 | tr '\n' ',' >> $file
bdrx
  • 924
  • 13
  • 31
0

An very old topic, but even now i have been needed to do this (on limited command resources) and that one (replied) command havent been working for me due to its length.

Appending to a file can be done also by using file-descriptors:

  • touch file.txt (create new blank file),

  • exec 100<> file.txt (new fd with id 100),

  • echo -n test >&100 (echo test to new fd)

  • exec 100>&- (close new fd)

Appending starting from specyfic character can be done by reading file from certain point eg.

  • exec 100 <> file.txt - new descriptor

  • read -n 4 < &100 - read 4 characters

  • echo -n test > &100 - append echo test to a file starting from forth character.

  • exec 100>&- - (close new fd)

BillyGL
  • 33
  • 5