Linux command (like cat) to read a specified quant

2019-01-21 04:48发布

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

9条回答
Deceive 欺骗
2楼-- · 2019-01-21 05:14

You can use dd to extract arbitrary chunks of bytes.

For example,

dd skip=1234 count=5 bs=1

would copy bytes 1235 to 1239 from its input to its output, and discard the rest.

To just get the first five bytes from standard input, do:

dd count=5 bs=1

Note that, if you want to specify the input file name, dd has old-fashioned argument parsing, so you would do:

dd count=5 bs=1 if=filename

Note also that dd verbosely announces what it did, so to toss that away, do:

dd count=5 bs=1 2>&-

or

dd count=5 bs=1 2>/dev/null
查看更多
戒情不戒烟
3楼-- · 2019-01-21 05:14

head:

Name

head - output the first part of files

Synopsis

head [OPTION]... [FILE]...

Description

Print the first 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when FILE is -, read standard input.

Mandatory arguments to long options are mandatory for short options too.
-c, --bytes=[-]N print the first N bytes of each file; with the leading '-', print all but the last N bytes of each file

查看更多
你好瞎i
4楼-- · 2019-01-21 05:15

you could also grep the line out and then cut it like for instance:

grep 'text' filename | cut -c 1-5

查看更多
登录 后发表回答