0

I'm trying to turn a list of numbers in a text file into python list form. For example, I want to make

1
2
3
4
5

into

[1,2,3,4,5]

I found something that almost worked in another post using sed.

sed '1s/^/[/;$!s/$/,/;$s/$/]/' file

but this didn't remove the new line after every number. How can I modify this sed command to get it to do what I want. Also, an explanation on the components of the sed command would also be appreciated. Thanks

Joshua Segal
  • 541
  • 1
  • 7
  • 19
  • `with open('file') as f:..data = f.read().strip().split();..nums = map(int, data)` ? Why are you using `sed` here ? – han solo Mar 23 '19 at 15:18
  • 8
    Are you wanting to do this in Python or is this primarily a question on `sed` and you're just referencing Python because of the format? If the later - you don't need anything except the `sed` tag... and if the former - you'd don't need the `sed` tag... Please considering making an [edit] to your post to clarify that - thanks. – Jon Clements Mar 23 '19 at 15:21
  • Just in case you need it for some out of python operation `awk 'BEGIN{RS=ORS="";OFS="," ;printf "["} {$1=$1;print} END{print "]\n"}' file` – P.... Mar 23 '19 at 15:31
  • Append `| tr -d '\n'`? – Cyrus Mar 23 '19 at 15:56
  • Thank you @Cyrus. That's a pretty good command line answer. You should make it an actual answer – Joshua Segal Mar 23 '19 at 21:00

4 Answers4

1

With GNU sed for -z to read the whole file at once:

sed -z 's/\n/,/g; s/^/[/; s/,$/]\n/' file
[1,2,3,4,5]

With any awk in any shell on any UNIX box:

$ awk '{printf "%s%s", (NR>1 ? "," : "["), $0} END{print "]"}' file
[1,2,3,4,5]
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

You can append all the lines into the pattern space first before performing substitutions:

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

This outputs:

[1,2,3,4,5]
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • when I do seq 5 | sed -z 's/^/[/; s/\n/,/g; s/,\?$/]\n/' it seems to not even change the output. It's identical to seq 5 – Joshua Segal Mar 23 '19 at 20:28
  • That isn't my code (that is oguzismail's code). Please run the demo here: https://tio.run/##K05N0U3PK/3/3yrR2s9aRTEp0bpYPyZPX0c/HciI04@J1gfSKvoxsfr//xtyGXEZc5lwmXIBAA – blhsing Mar 24 '19 at 02:53
0

This might work for you (GNU sed):

sed '1h;1!H;$!d;x;s/\n/,/g;s/.*/[&]/' file

Copy the first line to the hold space, append copies of subsequent lines and delete the originals. At the end of the file, swap to the hold space, replace newlines by commas, and surround the remaining string by square brackets.

potong
  • 55,640
  • 6
  • 51
  • 83
-1

If you want the list using python, a simple implementation is

with open('./num.txt') as f:
    num = [int(line) for line in f]
Merig
  • 1,751
  • 2
  • 13
  • 18
  • Thanks. I probably should have added that this is supposed to be more of a sed exercise, but thanks for the code snippet – Joshua Segal Mar 23 '19 at 20:16