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?

0

3 Answers 3

4

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

1
  • 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). Commented Aug 9, 2016 at 13:45
1

You could try

sed 's/\(.\{5\}\).*/\1/' file.txt
1
  • That is more readable with ERE: sed -rn 's/(.{5}).*/\1/p' file.txt
    – Law29
    Commented Aug 9, 2016 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 .