我必须在文件的第一行中放入一个bash变量。我想它是与grep命令,但它是任何方式来限制行数?


当前回答

这个问题并没有问哪个最快,但是添加到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

其他回答

line=$(head -1 file)

会很好。(和前面的答案一样)。但

line=$(read -r FIRSTLINE < filename)

将稍微快一点,因为read是内置的bash命令。

这个问题并没有问哪个最快,但是添加到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

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

line=$(head -n 1 filename)

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

read -r firstline<file

firstline将是你的变量(不需要分配给另一个)

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

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