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

守給你的承諾、 提交于 2019-12-03 02:07:43

问题


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


回答1:


You don't need cat.

head -1 file

will work fine.




回答2:


You don't, use head instead.

head -n 1 file.txt



回答3:


There are many different ways:

sed -n 1p file
head -n 1 file
awk 'NR==1' file



回答4:


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




回答5:


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



回答6:


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

 cat <file> | awk 'NR == 1'



回答7:


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.




回答8:


You dont need any external command if you have bash v4+

< file.txt mapfile -n1 && echo ${MAPFILE[0]}

or if you really want cat

cat file.txt | mapfile -n1 && echo ${MAPFILE[0]}

:)




回答9:


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

head -1 FileName.csv



来源:https://stackoverflow.com/questions/6114119/how-do-i-read-the-first-line-of-a-file-using-cat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!