2

this is my file

$ cat testjson2
[alot of text]

I would like to end up with below: ({ "aaData": append at the start of the file } appended at the end of the file)

{ "aaData": [alot of text] }


What I have got so far:

this does the appending at the start of the file

$ sed '1s/./{ "aaData": &/' testjson2
{ "aaData": [alot of text] } 

this does the appending at the end of the file

$ echo } >> testjson2
$ cat testjson2
[alot of text]
}

How do I combine them? maybe just using sed or should i just use this combination to get what I want? just looking at using sed awk or bash here.

HattrickNZ
  • 3,493
  • 12
  • 40
  • 82
  • See: [The Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/a/22944075/3776858) – Cyrus Sep 29 '16 at 01:51

2 Answers2

2

Try:

$ sed '1s/^/{ "aaData": /; $ s/$/ }/' testjson2
{ "aaData": [alot of text] }

This uses two substitute commands:

  • 1 s/^/{ "aaData": / adds text to the beginning of the first line.

    1 matches on line 1. ^ matches on the beginning of a line.

  • $ s/$/ }/ adds text after the end of the last line.

    The first $ matches the last line of the file. The second $ matches at the end of a the line.

John1024
  • 97,609
  • 11
  • 105
  • 133
2
$ awk '{printf "%s%s", (NR>1 ? ORS : "{ \"aaData\": "), $0} END{print " }"}' file
{ "aaData": [alot of text] }
Ed Morton
  • 157,421
  • 15
  • 62
  • 152
  • tks @ed. can you just give a brief explanation? what i know, `NR>1` on the first line, `? ORS` not sure output record separator, `END{print " }"}` is END the last line? , `printf "%s%s"` is the first %s for the first string at the start and the second %s for the 2nd string `}` to append at the end? – HattrickNZ Sep 29 '16 at 19:23
  • 1
    NR>1 AFTER the first line and the 2nd string for printf is $0. END is a condition that's true after all input has been read. IIRC you've posted several text manipulation questions - I recommend the book Effective Awk Programming, 4th Edition, by Arnold Robbins. – Ed Morton Sep 29 '16 at 20:05