Skip to content

Instantly share code, notes, and snippets.

@kugland
Created December 26, 2022 05:41
Show Gist options
  • Save kugland/2b32a84feb83fa21f9a0c6f6b4ce784a to your computer and use it in GitHub Desktop.
Save kugland/2b32a84feb83fa21f9a0c6f6b4ce784a to your computer and use it in GitHub Desktop.
lineinfile, similar to the Ansible action, in Perl
#!/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