Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

Add a comma to every curly bracket except the last curly bracket in Shell/awk/sed

I'd like to add a comma after } except the last one } Tried Google but can't find the answer.

Example as below:

From

{
  "{#SERVICES} ,": "Directory",
  "{#STATUS}": "RUNNING"
}
{
  "{#SERVICES}": "krb5kdc",
  "{#STATUS}": "RUNNING"
}
{
  "{#SERVICES}": "kadmin",
  "{#STATUS}": "RUNNING"
}
{
  "{#SERVICES}": "named",
  "{#STATUS}": "RUNNING"
}
{
  "{#SERVICES}": "httpd",
  "{#STATUS}": "RUNNING"
}

To

{
  "{#SERVICES} ,": "Directory",
  "{#STATUS}": "RUNNING"
},
{
  "{#SERVICES}": "krb5kdc",
  "{#STATUS}": "RUNNING"
},
{
  "{#SERVICES}": "kadmin",
  "{#STATUS}": "RUNNING"
},
{
  "{#SERVICES}": "named",
  "{#STATUS}": "RUNNING"
},
{
  "{#SERVICES}": "httpd",
  "{#STATUS}": "RUNNING"
}

Please let me know if you have any questions.

Thanks!!

question from:https://stackoverflow.com/questions/65931347/add-a-comma-to-every-curly-bracket-except-the-last-curly-bracket-in-shell-awk-se

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using awk:

awk -F '}
{' 'BEGIN { RS="" } { for(i=1;i<=NF;i++) { if (i==NF) { str=$i } else { str=$i"},
{" };printf "%s",str} print "
" }'

Set the field separator to "} {" and the record separator to "" and then loop on each field printing the field followed by "}, {" apart from the last field where we simply print the field.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...