Ubuntu – How to cat file with limit of printed characters from each line

command linetext processing

I would like to cat file, but with limit to max length to each line. For example I a have file with 10 lines each have 10000 characters and I would like to print first 100 characters from each line. Is something like that possible with cat or some alternative? thx.

Best Answer

With the cut tool you can limit the output to 100. Since you only interested in the characters hence the columns they occupy this should do that nicely:

cut -c-100 file

In case you wish to remove the spaces in there this would help:

sed 's/ //g' file | cut -c-100

See: man cut

Using awk:

awk '{ print substr( $0, 0, 100 ) }' file

Getting rid of spaces again if required:

awk '{ gsub (" ", "", $0); print substr( $0, 0, 100 ) }' file

AWK:

gsub (" ", "", $0): find " "(spaces) and replace with "" globally in target string $0.

substr( $0, 0, 100 ): it returns 100 number of chars from string $0, starting at position 0.