5

I have to replace the newline character with ',' for using in some oracle command but in a single command. I can't figure out how to do it.

Input:

R1
R2
R3
R4

Required Output:

'R1','R2','R3','R4'
informatik01
  • 16,038
  • 10
  • 74
  • 104
Learner
  • 1,544
  • 8
  • 29
  • 55

5 Answers5

4

In BBedit, you would use a grep like these for find:

(R[0-9]+)\r

and replace:

'\1', 
New Alexandria
  • 6,951
  • 4
  • 57
  • 77
2

Using tr:

cat data.txt | tr '\n' ','

If you need the quotes, you could pipe to sed:

cat data.txt | tr '\n' ',' | sed "s/,/','/g"

… which gets you pretty close:

R1','R2','R3','R4','
davidchambers
  • 23,918
  • 16
  • 76
  • 105
  • I am new to unix so could not understand why we can not directly replace newline with ',' characters – Learner Dec 24 '12 at 06:34
2

Using sed:

 sed -n '1h;1!H;${ g; s/\n/,/g; s/\([^,]*\)/'\''\1'\''/gp}' input
perreal
  • 94,503
  • 21
  • 155
  • 181
2

Here's one way using sed:

sed ":a;N;\$!ba;s/\n/','/g;s/^\|$/'/g" file

Results:

'R1','R2','R3','R4'
Steve
  • 51,466
  • 13
  • 89
  • 103
  • Thanks for replying while firing the command I am getting an error; "-bash: !ba: event not found" – Learner Dec 24 '12 at 06:06
1

The requirement to replace newlines does not match your sample output. To replace newlines with ,, you can do tr \\n ,, but this gives you output with a trailing comma that does not have a trailing newline. Also, it does not quote your input. Perhaps you are looking for:

paste -s -d, input

Or, if you do actually want the fields to be quoted:

< input sed "s/^\|$/'/g" | paste -s -d,

In the above, your input file is named input. The final command can also be written:

sed "s/^\|$/'/g" input | paste -s -d,
William Pursell
  • 204,365
  • 48
  • 270
  • 300