Home > Back-end >  How to remove a comma 2nd to the last line of the file using SED?
How to remove a comma 2nd to the last line of the file using SED?

Time:12-05

I'm trying to search and remove a comma , at the 2nd to the last line using sed.

This is what I have now:

}
   "user-account-id": "John",
   "user-account-number": "v1001",
   "user-account-app": "v10.0.0",
   "user-account-dbase": "v10.1.0",
}

I want the end result to be like this:

}
   "user-account-id": "John",
   "user-account-number": "v1001",
   "user-account-app": "v10.0.0",
   "user-account-dbase": "v10.1.0"
}

I thought I found the answer an hour after I posted this but I was wrong. It didn't work.

Dry run with any of these combination doesn't work:

sed '2,$ s/,$//' filename
sed '2,$ s/,//' filename
sed '2,$ s/,//g' filename
sed '2,$s/,$//' filename
sed '2,$s/,//' filename
sed '2,$s/,//g' filename

Actual removal with any of these combination doesn't work:

sed -i '2,$ s/,$//' filename
sed -i '2,$ s/,//' filename
sed -i '2,$ s/,//g' filename
sed -i '2,$s/,$//' filename
sed -i '2,$s/,//' filename
sed -i '2,$s/,//g' filename

I thought running sed with '2,$ would only modify "2nd to the last line" in the file.

The output would just delete commas in every line, which doesn't make sense:

}
   "user-account-id": "John"
   "user-account-number": "v1001"
   "user-account-app": "v10.0.0"
   "user-account-dbase": "v10.1.0"
}

CodePudding user response:

2,$ is a range starting at the 2nd line from the beginning and ending at the last line (so all lines except for the first one). Modifying the 2nd last line is hard in sed, see for example Replace the "pattern" on second-to-last line of a file.

But in your case, there is an easier solution with GNU sed:

Treat the entire file as one string and delete the last comma followed by an } at the end of the file (ignoring any whitespace, even linebreaks).

sed -Ez 's/,([ \t\r\n]*)\}([ \t\r\n]*)$/\1}\2/' file

In case you know the last

CodePudding user response:

Another tactic: reverse the file, remove the trailing comma on the first time it's seen, then re-reverse the file:

tac file  | awk -v p=1 'p && /,$/ {sub(/,$/, ""); p=0} 1' | tac
  • Related