简体   繁体   English

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

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

I have to put in a bash variable the first line of a file. 我必须在文件的第一行放入一个bash变量。 I guess it is with the grep command, but it is any way to restrict the number of lines? 我想这是用grep命令,但它是否有任何限制行数的方法?

head需要从文件中第一线,以及-n参数可用于指定多少线应该提取:

line=$(head -n 1 filename)

to read first line using bash, use read statement. 使用bash读取第一行,使用read语句。 eg 例如

read -r firstline<file

firstline will be your variable (No need to assign to another) firstline将是你的变量(不需要分配给另一个)

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. 要存储行本身,请使用var=$(command)语法。 In this case, line=$(awk 'NR==1 {print; exit}' file) . 在这种情况下, 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: 当我们用seq 10提供read时,查看样本,即1到10的数字序列:

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

$ line=$(awk 'NR==1 {print; exit}' <(seq 10))
$ echo "$line"
1
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命令,所以会略快一些。

只需将源文件的第一个列表echo显到目标文件中即可。

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

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. 问题并没有问哪个是最快的,但是为了添加到sed答案,-n'1p'表现不佳,因为模式空间仍在大文件上扫描。 Out of curiosity I found that 'head' wins over sed narrowly: 出于好奇,我发现“头部”以微弱优势赢得了胜利:

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM