Reputation: 1634
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'
Upvotes: 5
Views: 3828
Reputation: 7324
In BBedit, you would use a grep like these for find:
(R[0-9]+)\r
and replace:
'\1',
Upvotes: 4
Reputation: 212148
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,
Upvotes: 1
Reputation: 54392
Here's one way using sed
:
sed ":a;N;\$!ba;s/\n/','/g;s/^\|$/'/g" file
Results:
'R1','R2','R3','R4'
Upvotes: 2
Reputation: 97918
Using sed:
sed -n '1h;1!H;${ g; s/\n/,/g; s/\([^,]*\)/'\''\1'\''/gp}' input
Upvotes: 2
Reputation: 24806
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','
Upvotes: 2