我需要使用bash脚本从一个巨大的文本文件中反复删除第一行。
现在我正在使用sed - I -e "1d" $FILE -但它需要大约一分钟的时间来删除。
有没有更有效的方法来实现这个目标?
我需要使用bash脚本从一个巨大的文本文件中反复删除第一行。
现在我正在使用sed - I -e "1d" $FILE -但它需要大约一分钟的时间来删除。
有没有更有效的方法来实现这个目标?
当前回答
这一行代码可以做到:
echo "$(tail -n +2 "$FILE")" > "$FILE"
它可以工作,因为tail在echo之前执行,然后文件被解锁,因此不需要临时文件。
其他回答
如果您要做的是在失败后恢复,那么您可以构建一个包含迄今为止所做的工作的文件。
if [[ -f $tmpf ]] ; then
rm -f $tmpf
fi
cat $srcf |
while read line ; do
# process line
echo "$line" >> $tmpf
done
基于其他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
您可以使用-i来更新文件,而不使用'>'操作符。下面的命令将从文件中删除第一行并将其保存到文件中(在幕后使用临时文件)。
sed -i '1d' filename
因为听起来我不能加快删除,我认为一个好的方法可能是像这样批量处理文件:
While file1 not empty
file2 = head -n1000 file1
process file2
sed -i -e "1000d" file1
end
这样做的缺点是,如果程序在中间被杀死(或者如果其中有一些糟糕的sql -导致“进程”部分死亡或锁定),将会有行被跳过,或者被处理两次。
(file1包含SQL代码行)
可以使用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