繁体   English   中英

Linux:提取文件的第一行

[英]Linux: Extract the first line of a file

我正在使用OpenWrt和一个非常小的空间。

试图从文件中提取第一行。 该行需要进入变量并从文件中删除。 我可以使用head将它放入变量但不能使用tail因为据我所知,我将不得不做tail file > newFile并且我没有空间存放第二个文件。

有人知道一个更好的技术吗?

使用

sed -i -e '1 w /dev/stdout' -e '1d' file

编辑:您不能使用我的旧答案(见下文)与OpenWrt,因为OpenWrt不附带ed 多可惜。 所以这里有两种方法:

vi方式

vi也是一个真正的编辑器,所以以下内容将起作用:

vi -c ':1d' -c ':wq' file > /dev/null

我们用vi打开文件,并使用命令:1d删除第一行,然后:wq保存并退出,将所有输出重定向到/dev/null 凉爽,干净,简洁。

哦,你当然会跑:

firstline=$(head -n1 file)

在运行此vi命令之前,将文件的第一行放入变量firstline

注意。 在内存很少的系统上,当file很大时,此方法失败。

dd方式

dd是一个很酷的工具。 其他答案中给出的dd方法确实很棒,但它们依赖于openWrt不附带的truncate实用程序。 这是一个解决方法:

firstline=$(head -n1 file)
linelength=$(head -n1 file | wc -c)
newsize=$(( $(wc -c < file) - $linelength ))
dd if=file of=file bs=1 skip=$linelength conv=notrunc
dd if=/dev/null of=file bs=1 count=0 seek=$newsize

这将适用于大文件和非常小的内存! 最后一个dd命令扮演其他答案中给出的truncate命令的角色。


旧答案是:

您可以使用ed

firstline=$(printf '%s\n' 1p d wq | ed -s file.txt)

在每次调用时,您将获得变量firstline文件file.txt的第一行,并从文件中删除此行。

显示第一行并删除它:

 head -1 file
 sed -i 1d file

但是,这会隐式创建一个临时文件。 一个更好的解决方案可能是本文中指出的关于“就地”编辑文件的 海绵

我不会称之为优雅,但这是一种潜在的方式:

# Find the number of characters in the first line
BYTES=$(head -n 1 file | wc -c)
# Shift all the data in-place
dd if=file of=file bs=1 skip=$BYTES conv=notrunc
# Remove the extra bytes on the end
truncate -s -$BYTES file

没有任何标准实用程序( dd除外)可以在没有任何临时文件的情况下修改文件。

一个可行的解决方案是:

LINELENGTH=$(head -1 test.txt | wc -c)
tail -n +2 test.txt | dd of=test.txt conv=notrunc
truncate -s -$LINELENGTH test.txt

有关此主题的讨论,请参阅https://unix.stackexchange.com/a/11074/15241

编辑:

首先使用curl下载文件(参见注释)。 还有另一种选择:

curl URL | sed -e "1w first_line.txt" -e "1d" > rest.txt
firstline=$(cat first_line.txt)
rm first_line.txt

如果你有足够的ram:

contents=$(cat file) 
echo "$contents" | sed -n '1 !p' > file

或者,使用ed:

ed file
2,$wq

暂无
暂无

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

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