2

Based on How do I prevent sed -i from destroying symlinks?, but I use Perl.

I tried by middle of all these questions:

It was unsucessfull. Here is the little and simple sample:

#!/bin/perl
use strict; use warnings;

while (<>) 
{

  ## For all lines, replace all occurrences of #5c616c with another colour
  s/#5c616c/#8bbac9/g $(readlink -e -- "<>")

  ## $(readlink -e -- "<>") is similar to --in-place --follow-symlinks

  ## Print the line
  print;
}
Oo'-
  • 243
  • The first link solution you point out is particularly interesting for not having to complicate code. – Rui F Ribeiro Jan 06 '19 at 22:21
  • The codes in Shell are easy than in Perl, but I am not sure it is possible to make something similar in Shell to that in Perl. See the answer of terdon: https://unix.stackexchange.com/a/492724/232293 – Oo'- Jan 06 '19 at 22:28

1 Answers1

3

The readlink -e command is not portable so should not be relied upon.

$ cat input
Like quills upon the fretful porpentine.
$ ln -s input alink
$ readlink -e alink
readlink: illegal option -- e
usage: readlink [-n] [file ...]

Within the Perl code, instead replace the links with the filename it points to using Perl's readlink function then loop over the input as usual.

$ perl -i -ple 'BEGIN{for(@ARGV){ $_=readlink if -l }} tr/A-Z/a-z/' alink

alink is still a symbolic link and the contents of input have been modified:

$ perl -E 'say readlink "alink"'
input
$ cat input
LIKE QUILLS UPON THE FRETFUL PORPENTINE.

Within a Perl script this might look something like

#!/usr/bin/env perl
use strict;
use warnings;

for my $arg (@ARGV) {
    $arg = readlink $arg if -l $arg;
}

# in-place edit with backup filename, perldoc -v '$^I'
$^I = ".whoops";

while (readline) {
    s/#5c616c/#8bbac9/g;
    print;
}

though may need List::Util::uniq or similar to avoid modifying the same filename two or more times, if the input contains duplicate filenames.

thrig
  • 34,938
  • What if <> is necessary? See the first codes lines of terdon: https://unix.stackexchange.com/a/492724/232293. – Oo'- Jan 06 '19 at 22:09
  • <> is a less readable way to say readline. compare perl -MO=Deparse,-p -e '<>;readline' – thrig Jan 06 '19 at 23:16
  • Hi, I have tested it, it almost worked - it preserved the symlinks, but it made all unusual. You can download the small archive file: https://transfernow.net/f07ahfb8joa4 and test by yourself. – Oo'- Jan 07 '19 at 01:29