Skip to content
Advertisement

Replace very near word to a number with another word [closed]

Replace very near string to a number with another string

a b c d a b c d e 23:12:00 k b c l d b d c e 12:02:10

How to replace first d before time (number) with another character f.it should be as below

a b c d a b c f e 23:12:00 k b c l d b f c e 12:02:10

OR ,

How to Replace cell with header .

[srinivas@examplewww ~]$ grep -oP '(cell">)[0-2][0-9]+:[0-9]+:[0-9]+'  test.html1
cell">06:25:50
cell">23:59:38
cell">23:17:50
cell">06:27:37
cell">06:07:38

it should be as below

   header ">06:25:50
   header ">23:59:38
   header ">23:17:50
   header ">06:27:37
   header ">06:07:38

Advertisement

Answer

Following solution will search for any number and if found it will start polling backwards to search d in the string and if found replace it with b.

Sample input:

echo $x
a b c d a b c d e 23:12:00 k b c l d b d c e 12:02:10

Solution using awk:

echo $x |awk '{for(i=1;i<=NF;i++) if($i ~/[0-9]|-[0-9]/) for(j=i;j>=0;j--) if($j ~/d/) {gsub(/d/,"b",$j);break }}1'
a b c d a b c b e 23:12:00 k b c l d b b c e 12:02:10
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement