我想遍历文件并删除某些行。示例文件:在文件中循环并删除某些行
的test.txt
a
b
c
d
我有什么:
FILE=/tmp/test.txt
while read FILE
do
# if the line starts with b delete it otherwise leave it there
?
done
我想遍历文件并删除某些行。示例文件:在文件中循环并删除某些行
的test.txt
a
b
c
d
我有什么:
FILE=/tmp/test.txt
while read FILE
do
# if the line starts with b delete it otherwise leave it there
?
done
这是sed
一份工作 - 在UNIX流编辑器:
(sed '/^b/d' yourfile > yourfile~ && mv yourfile~ yourfile) || rm yourfile~
的命令将删除所有以开头的行210并将剩余行写入备份文件。如果成功,备份文件将被重命名为原始文件,如果失败备份文件将被删除。
你可以用grep的oneliner做到这一点:
grep -v "^b" test.txt > newfile
轻松使用bash完成内置功能:
while read -r; do
[[ $REPLY = b* ]] || printf '%s\n' "$REPLY"
done <file >file.new
mv file.new file
“的Perl ......它可能是你$PATH
”: - )
使用$SHELL
的微小文字的任务(即sh
,ksh
,zsh
,bash
,tcsh
,csh
)在BSD,OSX,Linux,AIX,Solaris上与各种“标准POSIX”相对于sed
,grep
和其他实用程序的BSD,Linux和GNU扩展,并注意考虑gawk
与awk
和古代版本许多服务器系统上的工具......可能很难。
perl -i.orig -ne 'print unless /^b/' test.txt
它工作吗?
diff test.txt test.txt.orig
'read'从标准输入中读取一行,而不是从文件中读取您期望的代码。你应该重定向'stdin'从文件中获取一行,请参阅:Duffy的答案。但是这个任务'sed'或'grep'更快。 – jm666
@ jm666较大文件较快,但不适用于较短文件。 'fork()'/'exec()'相比于只使用shell内建函数的东西是一个很大的开销。 –
@CharlesDuffy你是对的。在80线以下的笔记本中,bash速度更快。 80以上的sed速度更快,超过300行grep速度也更快。 :)取决于,你叫什么“大文件”:) – jm666