-
Notifications
You must be signed in to change notification settings - Fork 112
/
sed.pl
executable file
·122 lines (94 loc) · 2.29 KB
/
sed.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#!/usr/bin/env perl
use strict;
use warnings;
use File::Copy qw( move );
use File::Temp qw( tempfile );
use Getopt::Std qw( getopts );
sub usage ($);
my %opts;
getopts("ihs", \%opts)
or usage 1;
my $help = $opts{h};
if ($help) {
usage 0;
}
my $inplace = $opts{i};
my $single_str = $opts{s};
my $operation = shift or die "No operation specified.\n";
if (!@ARGV) {
warn "ERROR: no input file specified.\n\n";
usage 1;
}
my $total_hits = 0;
my $changed_files = 0;
for my $file (@ARGV) {
my ($out, $tmpfile);
if ($inplace) {
($out, $tmpfile) =
tempfile("sed-pl-XXXXXXX", UNLINK => 1, TMPDIR => 1);
}
my $hits = 0;
open my $in, $file
or die "Cannot open $file for reading: $!\n";
if ($single_str) {
my $old = do { local $/; <$in> };
$_ = $old;
#chomp;
if (eval $operation) {
$hits++;
if (!$inplace) {
require Text::Diff;
print "$file:$.: ", Text::Diff::diff(\$old, \$_);
#print "$file:$.: $_\n";
}
}
if ($inplace) {
print $out "$_\n";
}
} else {
while (<$in>) {
chomp;
if (eval $operation) {
$hits++;
if (!$inplace) {
print "$file:$.: $_\n";
}
}
if ($inplace) {
print $out "$_\n";
}
}
}
close $in;
$total_hits += $hits;
if ($inplace) {
close $out;
if ($hits) {
move $tmpfile, $file
or die "Cannot move $tmpfile to $file: $!\n";
$changed_files++;
}
}
}
warn "\nFound $total_hits hits.\n";
if ($total_hits) {
warn "Updated $changed_files files.\n";
if (!$inplace) {
warn " Hint: pass the -i option to actually update the files if the ",
"changes look good.\n";
}
}
sub usage ($) {
my $rc = shift;
my $msg = <<_EOC_;
Usage:
sed.pl [OPTION...] OPERATION INFILE...
Optons:
-h Print this help.
-i Do in-place substitution
-s Single string mode
Example:
sed.pl 's/(foo.*?)bar/${1}baz/gsm' `find lib -name '*.pm'`
Copyright (C) by Yichun Zhang. All rights reserved.
_EOC_
}