免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2736 | 回复: 5
打印 上一主题 下一主题

Perl中读入一个文件的一行后顺带把这一行在原文件中删除的操作?? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-03-29 12:14 |只看该作者 |倒序浏览
如题:Perl中读入一个文件的一行后顺带把这一行在原文件中删除的操作??

论坛徽章:
0
2 [报告]
发表于 2007-03-29 14:07 |只看该作者
use Tie::File



tie @file , 'Tie::File'  ,   "c:\xyf" or die "error !!!\n";

for (@file) {

s/Perl//g;

}

论坛徽章:
0
3 [报告]
发表于 2007-03-29 14:12 |只看该作者
我再说的详细一点,如何删除文件的第一行,或者最后一行??不必非要从文件中的某一行开始删除,最好不要用循环之类的方法,因为文件有十几万行,循环速度太慢了。

[ 本帖最后由 bluestarly 于 2007-3-29 14:14 编辑 ]

论坛徽章:
0
4 [报告]
发表于 2007-03-29 14:19 |只看该作者
use Tie::File;

tie @file , 'Tie::File'  ,   "c:\xyf" or die "error !!!\n";

pop @file;  #delete last line!!!
shift @file;  #delete first line!!


untie @file;  #finish!!!

论坛徽章:
0
5 [报告]
发表于 2007-03-29 14:20 |只看该作者
Please read Tie::File document if you have any further question.

论坛徽章:
0
6 [报告]
发表于 2007-03-29 16:52 |只看该作者

quickly remove one line from a file

Question:
1. 如题:Perl中读入一个文件的一行后顺带把这一行在原文件中删除的操作??
2. 如何删除文件的第一行,或者
3. 最后一行??


Answer:
simply using perl's option -i, -n, -e (See more perl -h)
1. unkown the line position, using regexp to match this line
    i.e.: match the required datetime
    perl -lne 'print if /^Mar 29 10:25:34/;' /var/log/auth.log
2. using specical var $.: $.== 1 is 1st. line from a file
    i.e.: get first line
     perl -lne 'print" if $.==1;' /var/log/auth.log
3. using builtin eof():  print "this is the last line($.)" if eof;
    i.e.: get last line
    perl -lne 'print "$.: $_" if eof;' /var/log/auth.log

Using s/// to remove found line

There are more another way to do that, ...

-- ulmer
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP