Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding double quotes, commas and removing newlines

I have a file that have a list of integers:

12542
58696
78845
87855
...

I want to change them into:

"12542", "58696", "78845", "87855", "..."

(no comma at the end)

I believe I need to use sed but couldnt figure it out how. Appreciate your help.

like image 798
Iokanaan Iokan Avatar asked Dec 03 '22 18:12

Iokanaan Iokan


2 Answers

You could do a sed multiline trick, but the easy way is to take advantage of shell expansion:

echo $(sed '$ ! s/.*/"&",/; $ s/.*/"&"/' foo.txt)

Run echo $(cat file) to see why this works. The trick, in a nutshell, is that the result of cat is parsed into tokens and interpreted as individual arguments to echo, which prints them separated by spaces.

The sed expression reads

$ ! s/.*/"&",/
$ s/.*/"&"/

...which means: For all but the last line ($ !) replace the line with "line",, and for the last line, with "line".

EDIT: In the event that the file contains not just a line of integers like in OP's case (when the file can contain characters the shell expands), the following works:

EDIT2: Nicer code for the general case.

sed -n 's/.*/"&"/; $! s/$/,/; 1 h; 1 ! H; $ { x; s/\n/ /g; p; }' foo.txt

Explanation: Written in a more readable fashion, the sed script is

s/.*/"&"/
$! s/$/,/
1 h
1! H
$ {
  x
  s/\n/ /g
  p
}

What this means is:

s/.*/"&"/

Wrap every line in double quotes.

$! s/$/,/

If it isn't the last line, append a comma

1 h
1! H

If it is the first line, overwrite the hold buffer with the result of the previous transformation(s), otherwise append it to the hold buffer.

$ {
  x
  s/\n/ /g
  p
}

If it is the last line -- at this point the hold buffer contains the whole line wrapped in double quotes with commas where appropriate -- swap the hold buffer with the pattern space, replace newlines with spaces, and print the result.

like image 157
Wintermute Avatar answered Dec 05 '22 06:12

Wintermute


Here is the solution,

sed 's/.*/ "&"/' input-file|tr '\n' ','|rev | cut -c 2- | rev|sed 's/^.//'

First change your input text line in quotes

sed 's/.*/ "&"/' input-file

Then, this will convert your new line to commas

tr '\n' ',' <your-inputfile>

The last commands including rev, cut and sed are used for formatting the output according to requirement.

Where,

rev is reversing string.

cut is removing trailing comma from output.

sed is removing the first character in the string to formatting it accordingly.

Output:

enter image description here

like image 38
Skynet Avatar answered Dec 05 '22 06:12

Skynet