How can I replace a word with text from earlier in the same line?

2

I have a text file that looks like this:

_map[0x00000044] = "screen";
_map[0x00000059] = "map";
_map[0x0000006e] = "info";

I would like to replace the words at the end of each line so my output looks like this:

_map[0x00000044] = "0044";
_map[0x00000059] = "0059";
_map[0x0000006e] = "006e";

I would like to update the file in-place. I tried the following but there must be a simpler way.

my $infile = 'newnumbers.txt';
open my $input, '<', $infile or die "Can't open to $infile: $!";   
my @finaldata = ();

while (<$input>){
    chomp;

    print "$1\n" if ($_ =~ /(0x0000.*])/);
    push(@finaldata, $1);
}
perl
asked on Stack Overflow Feb 20, 2014 by Mihir • edited Feb 20, 2014 by ThisSuitIsBlackNot

2 Answers

3
use strict;
use warnings;

my $infile = 'newnumbers.txt';

local @ARGV = ($infile);
local $^I = '.bac';
while( <> ){
    s/(_map\[0x[[:xdigit:]]{4}([[:xdigit:]]{4})\] = )".*"/$1"$2"/;
    print;
}

or if you're using a newer version of perl, the regex could be the following

s/_map\[0x[[:xdigit:]]{4}([[:xdigit:]]{4})\] = \K".*"/"$1"/;
answered on Stack Overflow Feb 20, 2014 by Miller • edited Feb 20, 2014 by ThisSuitIsBlackNot
0

How about this:

my $infile = $ARGV[0] || 'newnumbers.txt';
open FH, $infile;
my @lines = <FH>;
s/(_.*(\w{4})] = ")\w+(";)/$1$2$3/ foreach @lines;
print join '', @lines;
answered on Stack Overflow Feb 23, 2014 by Aldo

User contributions licensed under CC BY-SA 3.0