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

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

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


当前回答

对于那些使用非gnu的SunOS的人来说,下面的代码将会有所帮助:

sed '1d' test.dat > tmp.dat 

其他回答

因为听起来我不能加快删除,我认为一个好的方法可能是像这样批量处理文件:

While file1 not empty
  file2 = head -n1000 file1
  process file2
  sed -i -e "1000d" file1
end

这样做的缺点是,如果程序在中间被杀死(或者如果其中有一些糟糕的sql -导致“进程”部分死亡或锁定),将会有行被跳过,或者被处理两次。

(file1包含SQL代码行)

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

if [[ -f $tmpf ]] ; then
    rm -f $tmpf
fi
cat $srcf |
    while read line ; do
        # process line
        echo "$line" >> $tmpf
    done
tail +2 path/to/your/file

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

您可以使用-i来更新文件,而不使用'>'操作符。下面的命令将从文件中删除第一行并将其保存到文件中(在幕后使用临时文件)。

sed -i '1d' filename

基于其他3个答案,我想出了这个语法,在我的Mac OSx bash shell中完美地工作:

Line =$(head -n1 list.txt && echo "$(tail -n +2 list.txt)"> list.txt)

测试用例:

~> printf "Line #%2d\n" {1..3} > list.txt
~> cat list.txt
Line # 1
Line # 2
Line # 3
~> line=$(head -n1 list.txt && echo "$(tail -n +2 list.txt)" > list.txt)
~> echo $line
Line # 1
~> cat list.txt
Line # 2
Line # 3