Created
December 26, 2022 05:41
-
-
Save kugland/2b32a84feb83fa21f9a0c6f6b4ce784a to your computer and use it in GitHub Desktop.
lineinfile, similar to the Ansible action, in Perl
This file contains hidden or 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/env -S perl -CSD | |
# Usage: lineinfile <regexp> <new_value> <file1> <file2> <file3> ... | |
use strict; | |
use warnings; | |
use utf8; | |
if (@ARGV < 3) { | |
die "Usage: $0 <regexp> <new_value> <file1> <file2> <file3> ..." | |
} | |
my $regexp = shift; | |
my $new_value = shift; | |
for my $file (@ARGV) { | |
open my $tmp, '>', "$file.tmp" or die "Can't open $file.tmp: $!"; | |
if ((open my $fh, '<', $file)) { | |
my $found = 0; | |
for my $line (<$fh>) { | |
chomp $line; | |
if ($line =~ /$regexp/) { | |
$line = $new_value; | |
$found = 1; | |
} | |
print $tmp "$line\n"; | |
} | |
close $fh; | |
if (!$found) { | |
print $tmp "$new_value\n"; | |
} | |
} else { | |
print $tmp "$new_value\n"; | |
} | |
close $tmp; | |
rename "$file.tmp", $file or die "Can't rename $file.tmp to $file: $!"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment