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
How to get the first line of a file in a bash script?
提问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
head
takes the first lines from a file, and the -n
parameter 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 read
statement. eg
要使用 bash 读取第一行,请使用read
语句。例如
read -r firstline<file
firstline
will be your variable (No need to assign to another)
firstline
将是您的变量(无需分配给另一个)
回答by fedorqui 'SO stop harming'
This suffices and stores the first line of filename
in the variable $line
:
这足以将第一行存储filename
在变量中$line
:
read -r line < filename
I also like awk
for 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 read
with seq 10
, that is, a sequence of numbers from 1 to 10:
当我们输入read
with时看一个示例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 read
is a built-in bash command.
read
与内置 bash 命令一样,速度会稍快一些。
回答by openwonk
Just echo
the 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