tags:

views:

92

answers:

5

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?

A: 

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.

Jonathan Leffler
I think I'm probably not understanding the `sed` properly. Wouldn't a trailing newline cause the $ to jump to the empty line, upon which it would not find a comma and promptly exit?
jdmichal
No, `$` means "last line". The last line can end with `\n` (which is usually the case in UNIX); it will still be the last line.
ephemient
A: 

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 ]?

Matt
Thanks, this is exactly what I was looking for. And yes, you're right, I don't really care about whether or not there is a newline, I just want the comma replaced. Thanks!
Duane J
The command replaces all commas of the last line. You should use `'$ s/,$/]/'` if you want only the last comma replaced.
mouviciel
+1  A: 
perl -i -pe'BEGIN{undef$/}s/,\n?\Z/]/'
ephemient
A: 

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
Brian Bay
Brian, thanks for this one. I didn't realize until trying things out that the above suggestions replace *all* commas with closing square brackets rather. Your second sed statement is just what I was looking for.
Duane J
Umm, huh? Matt's answer is the only one that might be incorrect.
ephemient
no need for cat.
A: 

here's a faster method compared to use sed for big files, assuming last line is not a newline

head -n -1 file > temp;
s=$(tail -1 file)
echo ${s/%,/]} >> temp
echo mv temp file