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:

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
  • The first link solution you point out is particularly interesting for not having to complicate code. – Rui F Ribeiro Jan 6 '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](@terdon): unix.stackexchange.com/a/492724/232293 – Gustavo Reis Jan 6 '19 at 22:28

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"'
$ cat input

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) {

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

  • What if <> is necessary? See the first codes lines of [terdon](@terdon): unix.stackexchange.com/a/492724/232293. – Gustavo Reis Jan 6 '19 at 22:09
  • <> is a less readable way to say readline. compare perl -MO=Deparse,-p -e '<>;readline' – thrig Jan 6 '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: transfernow.net/f07ahfb8joa4 and test by yourself. – Gustavo Reis Jan 7 '19 at 1:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.