我需要使用bash脚本从一个巨大的文本文件中反复删除第一行。

现在我正在使用sed - I -e "1d" $FILE -但它需要大约一分钟的时间来删除。

有没有更有效的方法来实现这个目标?


当前回答

海绵util避免了对临时文件的杂耍:

tail -n +2 "$FILE" | sponge "$FILE"

其他回答

可以使用sed命令按行号删除任意行

# create multi line txt file
echo """1. first
2. second
3. third""" > file.txt

删除行并打印到标准输出

$ sed '1d' file.txt 
2. second
3. third

$ sed '2d' file.txt 
1. first
3. third

$ sed '3d' file.txt 
1. first
2. second

# delete multi lines
$ sed '1,2d' file.txt 
3. third

# delete the last line
sed '$d' file.txt 
1. first
2. second

使用-i选项就地编辑文件

$ cat file.txt 
1. first
2. second
3. third

$ sed -i '1d' file.txt

$cat file.txt 
2. second
3. third
tail +2 path/to/your/file

适用于我,不需要指定-n标志。原因请看Aaron的回答。

应该显示除第一行以外的其他行:

cat textfile.txt | tail -n +2

如果您要做的是在失败后恢复,那么您可以构建一个包含迄今为止所做的工作的文件。

if [[ -f $tmpf ]] ; then
    rm -f $tmpf
fi
cat $srcf |
    while read line ; do
        # process line
        echo "$line" >> $tmpf
    done

在N-1行上使用tail并将其定向到一个文件中,然后删除旧文件,并将新文件重命名为旧名称,这样做可以吗?

如果我以编程方式执行此操作,我将读取文件,并在读取每一行后记住文件偏移量,因此我可以查找回该位置以读取文件中少一行的文件。