Duane J
Duane J

Reputation: 1843

How to replace the last one or two characters of a file with unix tools

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?

Upvotes: 2

Views: 8859

Answers (5)

ghostdog74
ghostdog74

Reputation: 343201

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

Upvotes: 0

Brian Bay
Brian Bay

Reputation: 301

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 

Upvotes: 2

ephemient
ephemient

Reputation: 205034

perl -i -pe'BEGIN{undef$/}s/,\n?\Z/]/'

Upvotes: 1

Matt
Matt

Reputation: 2758

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

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 755104

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.

Upvotes: 1

Related Questions