I have a hanging comma at the end of a file that I would like to replace with a close square bracket. There may or may not be a newline character at the end of the file as well. How can I replace the one or two characters with the square bracket using common unix tools?
Generally, text files should end with a newline.
One way to edit a file for replace trailing comma with close bracket on last line is:
ed - $file <<'!'
$s/,$/]/
w
q
!
This goes to the last line, replaces the trailing comma with close bracket, and writes and exits. Alternatively, using sed:
sed '$s/,$/]/' $file > new.$file &&
mv new.$file $file
If you have GNU sed, there is an 'overwrite' option ('-i', IIRC).
If you need to deal with file names rather than file contents, then:
newname=$(echo "$oldname" | sed 's/,$/]/')
And no doubt there are other mechanisms too. You could also use Perl or Python; they tend towards overkill for the example requested.
Sed can easily do a replace on the last line only:
sed '$ s/,/]/g' inputFile
The $ address selector indicates the last line.
If the file ended with a newline, this would not change that, however. Is that really a desired behavior, or do you just want to replace the last , with ]?
This will delete all trailing empty lines and then replace the last comma in the file with a ']'
cat origfile | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' | sed -e '$s/,$/]/' > outputfile