bash 如何在bash脚本中获取文件的第一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2439579/
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 19:02:56  来源:igfitidea点击:

How to get the first line of a file in a bash script?

bash

提问by Neuquino

I have to put in a bash variable the first line of a file. I guess it is with the grep command, but it is any way to restrict the number of lines?

我必须在文件的第一行放入一个 bash 变量。我猜是用 grep 命令,但是有什么办法可以限制行数吗?

回答by sth

headtakes the first lines from a file, and the -nparameter can be used to specify how many lines should be extracted:

head从文件中获取第一行,该-n参数可用于指定应提取多少行:

line=$(head -n 1 filename)

回答by ghostdog74

to read first line using bash, use readstatement. eg

要使用 bash 读取第一行,请使用read语句。例如

read -r firstline<file

firstlinewill be your variable (No need to assign to another)

firstline将是您的变量(无需分配给另一个)

回答by fedorqui 'SO stop harming'

This suffices and stores the first line of filenamein the variable $line:

这足以将第一行存储filename在变量中$line

read -r line < filename

I also like awkfor this:

我也喜欢awk这个:

awk 'NR==1 {print; exit}' file

To store the line itself, use the var=$(command)syntax. In this case, line=$(awk 'NR==1 {print; exit}' file).

要存储行本身,请使用var=$(command)语法。在这种情况下,line=$(awk 'NR==1 {print; exit}' file)

Or even sed:

甚至sed

sed -n '1p' file

With the equivalent line=$(sed -n '1p' file).

line=$(sed -n '1p' file).



See a sample when we feed the readwith seq 10, that is, a sequence of numbers from 1 to 10:

当我们输入readwith时看一个示例seq 10,即从 1 到 10 的数字序列:

$ read -r line < <(seq 10) 
$ echo "$line"
1

$ line=$(awk 'NR==1 {print; exit}' <(seq 10))
$ echo "$line"
1

回答by Hymanbot

line=$(head -1 file)

Will work fine. (As previous answer). But

会工作得很好。(如上一个答案)。但

line=$(read -r FIRSTLINE < filename)

will be marginally faster as readis a built-in bash command.

read与内置 bash 命令一样,速度会稍快一些。

回答by openwonk

Just echothe first list of your source file into your target file.

只需echo将您的源文件的第一个列表放入您的目标文件中。

echo $(head -n 1 source.txt) > target.txt

回答by Neil McGill

The question didn't ask which is fastest, but to add to the sed answer, -n '1p' is badly performing as the pattern space is still scanned on large files. Out of curiosity I found that 'head' wins over sed narrowly:

问题没有问哪个最快,但要添加到 sed 答案中, -n '1p' 表现不佳,因为仍然在大文件上扫描模式空间。出于好奇,我发现 'head' 以微弱优势胜过 sed:

# best:
head -n1 $bigfile >/dev/null

# a bit slower than head (I saw about 10% difference):
sed '1q' $bigfile >/dev/null

# VERY slow:
sed -n '1p' $bigfile >/dev/null