in unix using simple command like sed how to print last character of a file?

link|improve this question
Do you care if the last character is actually "printable"? i.e. if the last character is a new line, is that ok? – DaveParillo Mar 3 '11 at 16:09
feedback

migrated from stackoverflow.com Mar 3 '11 at 14:16

This question came from our site for professional and enthusiast programmers.

6 Answers

tail is the right tool, not sed.

tail -c 1 filename
link|improve this answer
2  
+1 - For a text file, if you want the last character before the last newline, just replace 1 by 2 – mouviciel Mar 3 '11 at 13:09
feedback

Try this cat filename | tail -c -1

link|improve this answer
4  
Heh, first time I've ever seen "Your answer must be at least 30 characters". – irritate Mar 3 '11 at 13:06
3  
misuse of pipes, same pitfall as in cat foo | grep bar – vtest Mar 3 '11 at 15:27
@vtest: What are those pitfalls? – Eclipse Mar 3 '11 at 16:35
@vtest, maybe "Try this tail -c -1 filename" was too short answer (less than 30 chars), so additional cat | was added to prolong it. ;) – ulidtko Mar 3 '11 at 19:35
@ulidtko: I commented on the recipe, not on the answer length – vtest Mar 3 '11 at 23:18
feedback

tail -c 2 file should do it. Should be -c 1 in theory but practice proved me wrong.

Edit: If your file has a an end of life / eof character that you want to ignore, it's 2. 1 otherwise.

link|improve this answer
Maybe your test file has a newline at the end? – Delan Azabani Mar 3 '11 at 13:09
It indeed had one. – J.N. Mar 3 '11 at 13:10
I've never seen a file with an end of life character. – Paul R Mar 3 '11 at 13:49
feedback

This should work, provided that last line is not empty:

sed -n '$s/.*\(.\)$/\1/p' file
link|improve this answer
feedback

Use: cat test | sed -e "s/^.*\(.\)$/\1/"

where test is the name of your file.

link|improve this answer
feedback

this command will print the last character

echo "abc" | sed 's/^.*\(.\)$/\1/'
link|improve this answer
but not the last character of a file. – DaveParillo Mar 3 '11 at 16:12
feedback

Your Answer

 
or
required, but never shown