用perl写一个脚本 实现把文件A中重复内容的行删除
时间: 2024-04-29 14:22:35 浏览: 9
没有问题,以下是 perl 脚本代码:
```perl
#!/usr/bin/perl
use strict;
use warnings;
my $file = 'A.txt'; # 文件名
my %seen; # 用哈希表记录已出现的行
open(my $fh, '<', $file) or die "Can't open file $file: $!";
while (my $line = <$fh>) {
if (!$seen{$line}) { # 如果哈希表中没有出现过该行
print $line; # 输出该行
$seen{$line}++; # 将该行记录到哈希表中
}
}
close $fh;
```
你觉得如何,有更多问题可以继续问我哦。
相关问题
用perl写一个脚本 实现把文件A中内容重复的行只保留一个
好的, 以下是 perl 脚本的代码:
```perl
#!/usr/bin/perl
use strict;
use warnings;
my $filename = 'A.txt';
my %lines;
open(my $fh, '<', $filename) or die "Error opening file: $!";
while ( my $line = <$fh> ) {
chomp $line;
$lines{$line}++;
}
close($fh);
open(my $out_fh, '>', $filename) or die "Error opening file: $!";
foreach my $line ( keys %lines ) {
print $out_fh "$line\n";
}
close($out_fh);
print "File deduplicated successfully\n";
```
以上代码会读取文件 A.txt 中的所有行,并将它们存储到一个哈希表中。哈希表会自动去重,因为每一行都是作为哈希表的key存储的。最后再将去重后的结果写回到文件 A.txt 中。
用perl写个脚本,将目录下所有文件内容中 abc 改成 BCD
以下是一个简单的 Perl 脚本,可以将指定目录下所有文件中的 "abc" 替换为 "BCD":
```perl
#!/usr/bin/perl
use strict;
use warnings;
# 指定要替换的目录
my $dir = "/path/to/directory";
# 打开目录
opendir(my $dh, $dir) || die "Can't open directory: $!";
# 遍历目录中的文件
while (my $file = readdir($dh)) {
# 跳过 "." 和 ".." 目录
next if ($file eq "." or $file eq "..");
# 拼接文件路径
my $path = "$dir/$file";
# 判断是否为文件
if (-f $path) {
# 打开文件
open(my $fh, "<", $path) || die "Can't open file $path: $!";
# 读取文件内容
my $content = do { local $/; <$fh> };
# 替换字符串
$content =~ s/abc/BCD/g;
# 关闭文件
close($fh);
# 写入文件
open($fh, ">", $path) || die "Can't write file $path: $!";
print $fh $content;
close($fh);
}
}
# 关闭目录
closedir($dh);
```
使用方法:
1. 将上述脚本保存为一个以 `.pl` 结尾的文件,比如 `replace.pl`。
2. 修改脚本中的 `$dir` 变量为你要替换的目录路径。
3. 在终端中执行 `perl replace.pl` 命令即可。