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?

Raffael
  • 941

3 Answers3

4

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

user1700494
  • 2,202
  • 2
    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 09 '16 at 13:45
1

You could try

sed 's/\(.\{5\}\).*/\1/' file.txt
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
heemayl
  • 56,300