Perl 脚本用另一行更新文件的一行 [英] Perl script to update one row of a file with another

查看:51
本文介绍了Perl 脚本用另一行更新文件的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有文本格式的数据文件,其中有几行.现在有些行有错误的数据,我需要用那些有正确数据的行来更新.例如,

I have data files in text format which have several rows. Now there are certain rows that have wrong data which I need to update with those that have the correct data. For example,

Col1  Col2  Col3  Col4 .......
A1?%     A     foo  fooo .......
B€(2     B     .................  
C&6     Z     .................
A?04     Y     .................
B++3     Q     .................
C!5     C     .................
D*9     D     .................

实际数据不同,但这是它的简化版本.正如您所看到的,有某些 Col1,其中 A1 是 A,但 A4 是 Y,依此类推.其余的列 Col3、Col4 ... 取决于 Col2.因此,当 Col1(A1、A2、A3 等)中有 A 时,我需要检查 Col2 是否为 A.如果不是,我必须根据 A 所在的行更新 Col2、Col3 ....

The actual data is different but this is a simplified version of it. As you can see there are certain Col1 where A1 is A but A4 is Y and so on. The rest of the columns Col3, Col4 ... depend on Col2. So, I need to check if Col2 is A when there is an A in Col1 (A1, A2, A3 etc). If not I have to update Col2, Col3 .... based on the row where it is A.

这如何在 Perl 中实现.我知道这种操作可以在带有更新语句的数据库中完成,但我在这里没有那么奢侈,必须以编程方式进行.

How may this be accomplished in Perl. I know this kind of operations can be done in an database with an update statement but I don't have that luxury here and have to do it programatically.

文件以制表符分隔,数据是可以包含任何字母数字或 ascii 字符的字符串.

推荐答案

我这样做的方法是打开一个输入文件句柄和一个输出文件句柄,然后逐行通过文件检查列第一,如果没关系,只需将其按原样放入我的输出中即可.

The way I would do this is to open an input file handle and an output file handle, and go line by line through the file checking column one and, if its fine, just plop it into my output just as it is.

如果确实需要更改,我会创建一个包含必要更改的新行并将其放入我的输出文件中.

If it does need to change, I would make a new line with the necessary changes and put it into my output file as well.

这是一种简单的方法,虽然不是最好的/优雅的/任何东西,但可以快速为您提供所需的东西.

This is a simple approach, that while not the greatest/elegant/whatever, would give you what you need quickly.

这篇关于Perl 脚本用另一行更新文件的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆