I need to replace the following text:

"name":["abc1234"], age:"24" 


"name": "abc1234", age: "24"
  • Are you trying to edit JSON in sed? – choroba Dec 19 '17 at 16:00
  • yes . Its a json file – Atish Dec 19 '17 at 16:01
  • 1
    post the full json content OR a testable fragment – RomanPerekhrest Dec 19 '17 at 16:14
  • 2
    what's the rule of replacement? should it cut the digits from existing value abc1234 OR just replace with static string abc? Post a valid object notation – RomanPerekhrest Dec 19 '17 at 16:25
  • 1
    I don't see why this question got these many upvotes.. no code/research effort shown, only one sample line given without explanation.. should entire line be matched? only "name":[...] and so on... – Sundeep Dec 20 '17 at 5:44

If I understand correctly, you want do replace the "name" list by its first element. If this is the case try a Json processor:

jq '.name=.name[0]' ex.json

(adaptations to the unpost full example may be needed)

  • jq is not sed, which was specified in the question – user5359531 Aug 22 '18 at 15:00

The general answer is

man 7 regex

but specifically

sed -E 's/"name":\["abc1234"\], age:"24" /"name": "abc1234", age:"24"/g' file > new


sed -E 's/"name" *: *\["([^"]+)"\], *age *: *"([0-9]+)"/"name": "\1", age:"\2"/g' file > new
grep -E '"name" *: *\[' new
  • 2
    You can use the more portable -E instead of -r (it is supported by at least GNU and BSD/macOS sed). – terdon Dec 19 '17 at 16:58
  • I had chosen -r to empasize the portability issue. Apparently though, recent versions of the GNU sed manual advocate -E and say it's being added to POSIX. I'll edit. – n.caillou Dec 19 '17 at 18:15

Another option would be using the Python JSON module as in this SO answer. Here's a simple example:

  • in.json

    { "name":["abc1234"], "age":"24" }
  • replaceInJson.py

    import json
    with open("in.json", "r") as f:
        data = json.load(f)
        print("Before:", data)
        data["name"] = data["name"][0]
        print("After: ", data)
  • Output

    Before: {'name': ['abc1234'], 'age': '24'}
    After:  {'name': 'abc1234', 'age': '24'}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.