How do I read first line using cat

2019-03-07 20:40发布

How do i read the first line of a file using cat?

标签: bash cat
9条回答
祖国的老花朵
2楼-- · 2019-03-07 21:03

You don't need cat. head -1 file will work fine.

查看更多
我命由我不由天
3楼-- · 2019-03-07 21:05

You could use cat file.txt | head -1, but it would probably be better to use head directly, as in head -1 file.txt.

查看更多
劳资没心,怎么记你
4楼-- · 2019-03-07 21:05

cat alone may not be possible, but if you don't want to use head this works:

 cat <file> | awk 'NR == 1'
查看更多
虎瘦雄心在
5楼-- · 2019-03-07 21:08

I'm surprised that this question has been around as long as it has, and nobody has provided the pre-mapfile built-in approach yet.

IFS= read -r first_line <file

...puts the first line of the file in the variable expanded by "$first_line", easy as that.

Moreover, because read is built into bash and this usage requires no subshell, it's significantly more efficient than approaches involving subprocesses such as head or awk.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-03-07 21:14

This may not be possible with cat. Is there a reason you have to use cat?

If you simply need to do it with a bash command, this should work for you:

head -n 1 file.txt
查看更多
Fickle 薄情
7楼-- · 2019-03-07 21:14

use the below command to get the first row from a CSVfile

head -1 FileName.csv

查看更多
登录 后发表回答