I have a variable

 local= "[  'service center','New'  ]"

I have used the following awk code to remove the square braces and single quotes,

 local=gensub(/[\[\]']+/, "", "g", local);

Expected O/P is

local ="  service center,New  "

The code I wrote is not working

  • 1
    Please provide some more context. I think you might better of using a json parser instead of trying to remove characters from your string. And please fix your code as it's not valid. – RoVo Feb 1 at 14:53
  • Can you see my updated question – mittu Feb 1 at 14:58
  • Still no context. And if it's all inside awk, you might want to remove the shell tag from the question. – RoVo Feb 1 at 15:08
  • What exactly is not working. The AWK substitution local=gensub(/[\[\]']+/, "", "g", local); produces exactly the expected value. The expression /[^,[:punct:][:space:]]/ you removed with your edit does not match "([:punct:] or [:space:]) and not ," but "not ([:punct:] or [:space:] or ,)". – Bodo Feb 1 at 15:09
  • 1
    @mittu Works for me. I think you should edit your question to include a complete, piece of awk code that exhibits the issue so any readers can repeat it. – ilkkachu Feb 1 at 15:36

You can replace commas with a non-punctuation character, remove all remaining puctuation, then restore the commas:

awk -v  local="[  'service center','New'  ]" '
    gsub(/,/, SUBSEP, local)
    gsub(/[[:punct:]]/, "", local)
    gsub(SUBSEP, ",", local)
    printf("local=\"%s\"\n", local)
local="  service center,New  "

Here, I'm using the builtin SUBSEP variable, described in the GNU awk manual thusly:

The default value of SUBSEP is the string "\034", which contains a nonprinting character that is unlikely to appear in an awk program or in most input data


Please find below command and it worked fine

cat filename
local= "[  'service center','New'  ]"

sed "s/[^a-zA-Z,= \" ]//g"  filename
output: local= "  service center,New  "

Command:  sed "s/[^a-zA-Z,= \" ]//g" filename

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.