Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1088271
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T23:03:02+00:00 2026-05-16T23:03:02+00:00

I have a file and a list of string pairs which I get from

  • 0

I have a file and a list of string pairs which I get from another file. I need substitute the first string of the pair with the second one, and do this for each pair.
Is there more efficient/simple way to do this (using Perl, grep, sed or other), then running a separate regexp substitution for each pair of values?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T23:03:02+00:00Added an answer on May 16, 2026 at 11:03 pm
    #! /usr/bin/perl
    
    use warnings;
    use strict;
    
    my %replace = (
      "foo" => "baz",
      "bar" => "quux",
    );
    
    my $to_replace = qr/@{["(" .
                           join("|" => map quotemeta($_), keys %replace) .
                           ")"]}/;
    
    while (<DATA>) {
      s/$to_replace/$replace{$1}/g;
      print;
    }
    
    __DATA__
    The food is under the bar in the barn.
    

    The @{[...]} bit may look strange. It’s a hack to interpolate generated content inside quote and quote-like operators. The result of the join goes inside the anonymous array-reference constructor [] and is immediately dereferenced thanks to @{}.

    If all that seems too wonkish, it’s the same as

    my $search = join "|" => map quotemeta($_), keys %replace;
    my $to_replace = qr/($search)/;
    

    minus the temporary variable.

    Note the use of quotemeta—thanks Ivan!—which escapes the first string of each pair so the regular-expression engine will treat them as literal strings.

    Output:

    The bazd is under the quux in the quuxn.

    Metaprogramming—that is, writing a program that writes another program—is also nice. The beginning looks familiar:

    #! /usr/bin/perl
    
    use warnings;
    use strict;
    
    use File::Compare;
    
    die "Usage: $0 path ..\n" unless @ARGV >= 1;
    
    # stub
    my @pairs = (
      ["foo"     => "baz"],
      ["bar"     => "quux"],
      ['foo$bar' => 'potrzebie\\'],
    );
    

    Now we generate the program that does all the s/// replacements—but is quotemeta on the replacement side a good idea?—

    my $code =
      "sub { while (<>) { " .
      join(" " => map "s/" . quotemeta($_->[0]) .
                      "/"  . quotemeta($_->[1]) .
                      "/g;",
                  @pairs) .
      "print; } }";
    #print $code, "\n";
    

    and compile it with eval:

    my $replace = eval $code
      or die "$0: eval: $@\n";
    

    To do the replacements, we use Perl’s ready-made in-place editing:

    # set up in-place editing
    $^I = ".bak";
    my @save_argv = @ARGV;
    
    $replace->();
    

    Below is an extra nicety that restores backups that the File::Compare module judges to have been unnecessary:

    # in-place editing is conservative: it creates backups
    # regardless of whether it modifies the file
    foreach my $new (@save_argv) {
      my $old = $new . $^I;
      if (compare($new, $old) == 0) {
        rename $old => $new
          or warn "$0: rename $old => $new: $!\n";
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a file with multiple list of (String,String,Int): [(aaa,aaaaaaaa,13),(asdasdasd,asdea,13)] and I need to
Ok so I have the following code: string numbers = File.ReadAllText(numbers.txt); StringSplitOptions.RemoveEmptyEntries); List<string> List
I have a list of keywords in a keywords.txt file. I have another file
I have a file with a list of regex patterns and string containing '\n's'
Does File.list() have a longer run time if there are more files in its
I have a php file list.php <?php $arr=array('444','555'); echo var_export($arr); ?> Now I want
I have a file containing a list of filenames: esocket.c esocket.h dockwin.cpp dockwin.h makefile
I have a file that contain list of numbers that looks like this: 10^-92
I have long file with the following list: /drivers/isdn/hardware/eicon/message.c//add_b1() /drivers/media/video/saa7134/saa7134-dvb.c//dvb_init() /sound/pci/ac97/ac97_codec.c//snd_ac97_mixer_build() /drivers/s390/char/tape_34xx.c//tape_34xx_unit_check() (PROBLEM)/drivers/video/sis/init301.c//SiS_GetCRT2Data301() /drivers/scsi/sg.c//sg_ioctl()
I have a file that essentially a list of XPaths like so: /Options/File[1]/Settings[1]/Type[1] /Options/File[1]/Settings[1]/Path[1]

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.