0

I know how to echo / add text to the end of a file:

echo "{ "fruit":"apple" , "amount":"10" }" >> file.txt

My question is how to add a object to the json file below:

the file - file.txt (empty):

{
"fruit": [

]
}

Expected result:

{
"fruit": [
{ "fruit":"apple" , "amount":"10" } #object to add

]
}
3
  • 2
    Don't use bash for that, but use a real JSON library. Commented Nov 11, 2012 at 18:47
  • totally agree, but the my question is; how to add text to the 'middle' of a file with bash. In this case a json file. Commented Nov 11, 2012 at 18:49
  • What's the specification of where the object should be added? It can be done with sed, awk, perl, etc. but you need to define the problem in more detail. Commented Nov 11, 2012 at 18:52

2 Answers 2

6

ed is the standard text editor.

#!/bin/bash

{
ed -s file.json <<EOF
/\"fruit\": \[
a
{ "fruit":"apple" , "amount":"10" } #object to add
.
wq
EOF
} &> /dev/null

Don't know why you want to use bash for that, though, there are much better tools around!

Done.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this one:

$ sed -e '/"fruit":/a{ "fruit":"apple" , "amount":"10" }' file.txt

This will add a line after "fruit". If you want to replace the file with the modified text:

$ sed -i.bak -e '/"fruit":/a{ "fruit":"apple" , "amount":"10" }' file.txt

will add the line and replace the file with the modified content. The old file will be saved as backup file.txt.bak.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.