bash 如何使用 cat 读取文件的第一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6114119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:33:03  来源:igfitidea点击:

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

bashfile-iocat

提问by Doboy

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

如何使用 读取文件的第一行cat

回答by Carl Norum

You don't need cat.

你不需要cat.

head -1 file

will work fine.

会正常工作。

回答by Orbling

You don't, use headinstead.

你不要,head改用。

head -n 1 file.txt

回答by JJJ

There are many different ways:

有很多不同的方式:

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

回答by Mike Pelley

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

您可以使用cat file.txt | head -1,但直接使用 head 可能会更好,如head -1 file.txt.

回答by mwcz

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

使用cat. 你有理由使用cat吗?

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

如果您只需要使用 bash 命令执行此操作,这应该适合您:

head -n 1 file.txt

回答by josh.trow

catalone may not be possible, but if you don't want to use headthis works:

cat单独可能是不可能的,但如果你不想使用head这个作品:

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

回答by Charles Duffy

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.

我很惊讶这个问题一直存在,而且还没有人提供 pre-mapfile 内置方法。

IFS= read -r first_line <file

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

...将文件的第一行放在由 展开的变量中"$first_line",就这么简单。

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

此外,由于read内置于 bash 中,并且这种用法不需要​​子 shell,因此它比涉及子进程的方法(如head或 )要高效得多awk

回答by jm666

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

如果您有 bash v4+,则不需要任何外部命令

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

or if you really want cat

或者如果你真的想要 cat

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

:)

:)

回答by Praveenkumar Sekar

Use the below command to get the first row from a CSV file or any file formats.

使用以下命令从 CSV 文件或任何文件格式中获取第一行。

head -1 FileName.csv