Created
September 5, 2018 03:54
-
-
Save geraldlai/84a19f6187fbd56fd3ad83d8fbcbae4c to your computer and use it in GitHub Desktop.
wgrep: write grep output back as changes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
# wgrep: write grep output back as changes | |
# ( requires 'ed' line editor ) | |
# $ grep -Rn foo . | sed 's/foo/bar/' | wgrep | |
# ( 'wgrep -a' avoids trimming trailing spaces by default ) | |
# Author: Gerald Lai | |
# License: 0BSD | |
use warnings; | |
use strict; | |
my $failed = 0; | |
my ($cur_file, $ED); | |
my $trim_end = 1; | |
if (@ARGV && $ARGV[0] eq "-a") { | |
$trim_end = 0; | |
shift @ARGV; | |
} | |
while (<>) { | |
chomp; | |
my $orig = $_; | |
s{\s+$}{} if $trim_end; | |
my $is_grep_line = s{^([^:]+?)[-:](\d+)[-:](?:\d+[-:])?}{}; | |
my $file = $1; | |
my $lnum = $2; | |
next unless /\S/; | |
if ($is_grep_line) { | |
if (!defined($cur_file) || $file ne $cur_file) { | |
if (defined($cur_file) && $ED) { | |
print $ED "w\n"; | |
close $ED; | |
warn "Wrote: $cur_file\n"; | |
$ED = undef; | |
} | |
if (-f $file && -r _ && -w _) { | |
open($ED, "|-", qw(ed -s), $file) or do { | |
$ED = undef; | |
}; | |
} | |
unless ($ED) { | |
$failed = 1; | |
warn "Error: Cannot modify $file\n"; | |
} | |
} | |
$cur_file = $file; | |
if ($ED) { | |
print $ED $lnum . "c\n", "$_\n", ".\n"; | |
next; | |
} | |
} | |
warn "Skipped: $orig\n"; | |
} | |
if ($ED) { | |
print $ED "w\n"; | |
close $ED; | |
warn "Wrote: $cur_file\n"; | |
} | |
exit $failed; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment