Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash regex finding and replacing

Tags:

bash

sed

awk

I don't know if this is possible, but can you dynamically alter a find/replace? Basically I have something like this

<3 digit number> <data>

and what I want to do is if data matches the pattern

<word>:<4 digit number>

replace all instances (in the entire file) of <word>: with the line's 3 digit number I.E:

020 Word
021 Word:0001
Replace with 
020 021
021 0210001

Is this doable with AWK or Sed? If not, is it doable in C?

like image 406
0zymandias Avatar asked May 09 '26 21:05

0zymandias


2 Answers

I know this isn't what you asked, but I think the best way to solve this is with a simple Perl script.

#!/usr/bin/perl

$in= "input.txt";
$out= "output.txt";

# Buffer the whole file for replacing:
open(INFILE, $in);
@lines = <INFILE>;
open(INFILE, $in);

# Iterate through each line:
while(<INFILE>) {
  # If the line matches "word:number", replace all instances in the file
  if (/^(\d{3}) (\w+:)\d{4}$/) {
    $num = $1; word = $2;
    s/$word/$num/ foreach @lines;
  }
}

open(OUTFILE, $out);
print OUTFILE foreach @lines;

It looks a lot longer than it really needs to be, because I made it nice and easy-to-read for you.

like image 82
Chriszuma Avatar answered May 11 '26 15:05

Chriszuma


I hope this time I got you right.

try the stuff below:

#file name:t
kent$  cat t
020 Word
021 Word:0001

#first we find out the replacement, 021 in this case:
kent$  v=$(grep -oP "(\d{3})(?= Word:\d{4})" t|head -n1)

#do replace by sed:
kent$  sed -r "s/Word[:]?/$v/g" t                                                                                                        
020 021 
021 0210001
like image 45
Kent Avatar answered May 11 '26 15:05

Kent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!