Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing all occurrence after nth occurrence in a line in perl

Tags:

sed

awk

perl

I need to replace all occurrences of a string after nth occurrence in every line of a Unix file.

My file data:

:account_id:12345:6789:Melbourne:Aus
:account_id:98765:43210:Adelaide:Aus

My output data:

:account_id:123456789MelbourneAus
:account_id:9876543210AdelaideAus

tried using sed: sed 's/://3g' test.txt

Unfortunately, the g option with the occurrence is not working as expected. instead, it is replacing all the occurrences.

like image 860
nag Avatar asked Nov 28 '22 10:11

nag


2 Answers

Another approach using awk

awk -v c=':' -v n=2 'BEGIN{
                       FS=OFS=""
                     }
                     {
                       j=0;
                       for(i=0; ++i<=NF;)
                         if($i==c && j++>=n)$i=""
                     }1' file 
$ cat file 
:account_id:12345:6789:Melbourne:Aus
:account_id:98765:43210:Adelaide:Aus

$ awk -v c=':' -v n=2 'BEGIN{FS=OFS=""}{j=0;for(i=0; ++i<=NF;)if($i==c && j++>=n)$i=""}1' file 
:account_id:123456789MelbourneAus
:account_id:9876543210AdelaideAus

like image 153
Akshay Hegde Avatar answered Dec 20 '22 00:12

Akshay Hegde


With GNU awk, using gensub please try following. This is completely based on your shown samples, where OP wants to remove : from 3rd occurrence onwards. Using gensub to segregate parts of matched values and removing all colons from 2nd part(from 3rd colon onwards) in it as per OP's requirement.

awk -v regex="^([^:]*:)([^:]*:)(.*)" '
{
  firstPart=restPart=""
  firstPart=gensub(regex, "\\1 \\2", "1", $0)
  restPart=gensub(regex,"\\3","1",$0)
  gsub(/:/,"",restPart)
  print firstPart restPart
}
' Input_file
like image 45
RavinderSingh13 Avatar answered Dec 19 '22 23:12

RavinderSingh13