Yasser B. Yasser B. - 1 month ago 11
JSON Question

How to delete the last character of prior line with sed

I'm trying to delete a line with a the last character of the prior line with sed :

I have a json file :

{
"name":"John",
"age":"16",
"country":"Spain"
}


I would like to delete country of all entries, to do that I have to delete the comma for the json syntax of the prior line.

I'm using this pattern :

sed '/country/d' test.json
sed -n '/resolved//.$//{x;d;};1h;1!{x;p;};${x;p;}' test.json

Answer

Bertrand Martel's helpful jq answer is the way to go, but if installing jq is not an option, try this GNU sed command:

$ sed -zr 's/,\s+"country":[^\n]+//g' test.json
{
"name":"John",
"age":"16"
}
  • -z splits the input into records by NULs, which, in this case means that the whole file is read at once, which enables cross-line substitutions.

  • -r enables extended regular expressions for a more modern syntax with more features.

  • s/,\n"country":\s+//g replaces all occurrences of a comma followed by a whitespace (including possibly a newline starting with "country" through the end of that line with the empty string, i.e., effectively removes the matched strings.

    • Note that this assumes that no other property follows such a country property on the same line.