HattrickNZ
HattrickNZ

Reputation: 4663

add string to the beginning of a file and another string to the end of a file

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.

Upvotes: 2

Views: 238

Answers (2)

Ed Morton
Ed Morton

Reputation: 204381

$ awk '{printf "%s%s", (NR>1 ? ORS : "{ \"aaData\": "), $0} END{print " }"}' file
{ "aaData": [alot of text] }

Upvotes: 2

John1024
John1024

Reputation: 113934

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.

Upvotes: 2

Related Questions