1

I have a text file of million lines to precess on UNIX as below:

"item"
"item"
"item"
"item"

And I use sed -i "s/$/,/g" filename > new_file to add comma at the end of each line.

What I expected is this way:

["item",
"item",
"item",
"item"]

Now, I am just using Vim to edit manually. Is there anyway to add brackets at the beginning and ending automatically with removing the comma at last line? So that, I could write a bash script to process these text files neatly.

Thanks!

Patrick
  • 2,889
  • 1
  • 24
  • 24

1 Answers1

3
sed -e '1s/^/[/' -e 's/$/,/' -e '$s/,$/]/' file_name > new_file

The only funny bit is replacing the comma added to the last line with the close square bracket.

Also note that using -i means there will be no output to standard output. Either use -i or use I/O redirection but not both. (And if you're a portability nut — like me — note that Mac OS X or BSD sed supports -i but requires a suffix for the backup. It will quite happily use -e as the suffix, if there's a -e after the -i, or use the sed script if you don't specify a -e — but then it complains about the file name not being a valid sed script).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278