linuxcommand-line

Linux command (like cat) to read a specified quantity of characters


Is there a command like cat in linux which can return a specified quantity of characters from a file?

e.g., I have a text file like:

Hello world
this is the second line
this is the third line

And I want something that would return the first 5 characters, which would be "hello".

thanks


Solution

  • head works too:

    head -c 100 file  # returns the first 100 bytes in the file
    

    ..will extract the first 100 bytes and return them.

    What's nice about using head for this is that the syntax for tail matches:

    tail -c 100 file  # returns the last 100 bytes in the file
    

    You can combine these to get ranges of bytes. For example, to get the second 100 bytes from a file, read the first 200 with head and use tail to get the last 100:

    head -c 200 file | tail -c 100