tru64gurus
tru64gurus

Reputation: 1

Search and replace text pattern

I am looking for a way to search/replace portion of the text in some of the values. In this example, I am looking to search for "abc" and replace with "xyz".

I tried this command without any luck:

jq -r '.[].name | |= if . contains("abc") then . = gsub("abc","XYZ") else . end' testfile 

[
  {
    "id": 202,
    "name": "abctext123",
    "module_name": "xxxxxxxxxxx"
  },
  {
    "id": 223,
    "name": "abcanothertext789",
    "module_name": "yyyyyyyyyyy"
  },
  {
    "id": 202,
    "name": "anypattern",
    "module_name": "zzzzzzzzzzz"
  },
  {
    "id": 223,
    "name": "anothertest",
    "module_name": "anothervalue"
  }
]

Expected output

[
  {
    "id": 202,
    "name": "XYZtext123",
    "module_name": "xxxxxxxxxxx"
  },
  {
    "id": 223,
    "name": "XYZanothertext789",
    "module_name": "yyyyyyyyyyy"
  },
  {
    "id": 202,
    "name": "anypattern",
    "module_name": "zzzzzzzzzzz"
  },
  {
    "id": 223,
    "name": "anothertest",
    "module_name": "anothervalue"
  }
]

Upvotes: 0

Views: 52

Answers (1)

choroba
choroba

Reputation: 242343

No need for "contains". If there's no abc, it won't be replaced.

[ .[] | .name |= gsub("abc"; "XYZ") ]

or, shorter and cleaner using map:

map(.name |= gsub("abc"; "XYZ"))

If the condition is different, the correct syntax is

map(.name |= if contains("abc") then gsub("abc"; "XYZ") else . end)

or

[ .[] | .name |= if contains("abc") then gsub("abc"; "XYZ") else . end ]

Upvotes: 3

Related Questions