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'
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'
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','
In BBedit, you would use a grep like these for find:
(R[0-9]+)\r
and replace:
'\1',
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','
Using sed:
sed -n '1h;1!H;${ g; s/\n/,/g; s/\([^,]*\)/'\''\1'\''/gp}' input
([^,]*)
needs to be \([^,]*\)
–
Valdes s/([^,]*)/
it needs to be s/\([^,]*\)/
. –
Demi echo $SHELL
on your terminal? –
Demi Here's one way using sed
:
sed ":a;N;\$!ba;s/\n/','/g;s/^\|$/'/g" file
Results:
'R1','R2','R3','R4'
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,
© 2022 - 2024 — McMap. All rights reserved.