0

I would like to print the tail of a file (could be also head or cat in general) to the screen but restrict the number of characters per line.

So if a file contains ...

abcdefg
abcd
abcde
abcdefgh

... and the maximum number is 5, then the following should be printed:

abcde
abcd
abcde
abcde

How would I do that?

marked as duplicate by don_crissti, Rahul, Stephen Harris, roaima, Jeff Schaller Aug 9 '16 at 15:06

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3

tail yourfile |cut -c 1-5
....

  • 1
    Note that in the case of current versions of GNU cut, that only works for single-byte characters (it returns only the first 5 bytes of each line). Hopefully, that will be fixed in a future version (some vendors like RedHat I believe have patches for that). – Stéphane Chazelas Aug 9 '16 at 13:45
1

You could try

sed 's/\(.\{5\}\).*/\1/' file.txt
  • That is more readable with ERE: sed -rn 's/(.{5}).*/\1/p' file.txt – Law29 Aug 9 '16 at 13:26
1

So many ways:

grep:

$ tail file.txt | grep -o '^.\{,5\}' 
abcde
abcd
abcde
abcde

sed:

$ tail file.txt | sed 's/^\(.\{,5\}\).*/\1/'
abcde
abcd
abcde
abcde

awk:

$ tail file.txt | awk '{print substr($0,1,5)}'
abcde
abcd
abcde
abcde

Not the answer you're looking for? Browse other questions tagged or ask your own question.