Question

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'
Was it helpful?

Solution 4

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','

OTHER TIPS

Using sed:

 sed -n '1h;1!H;${ g; s/\n/,/g; s/\([^,]*\)/'\''\1'\''/gp}' input

Here's one way using sed:

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

Results:

'R1','R2','R3','R4'

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

(R[0-9]+)\r

and replace:

'\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,
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top