kiran Biradar
kiran Biradar

Reputation: 12742

Replace every second instance of word in each line of the file

I'm trying to replace every second instance word of each line with sed.

For example: If I had a line as below

i_ref_clk i_ref_clk i_ait_rstn i_ait_rstn abc kiran/def

should be replaced as below.

i_ref_clk kiran/i_ref_clk i_ait_rstn kiran/i_ait_rstn abc def kiran/def

Only second instance of word is replaced with kiran/.

My attempt :

echo " i_ref_clk i_ref_clk i_ait_rstn i_ait_rstn abc def def" | sed 's/ / kiran\//2'

Output:

i_ref_clk kiran/i_ref_clk i_ait_rstn i_ait_rstn abc def def

My Question:

Please help me with the proper sed or any Linux command which does the above job.

Upvotes: 1

Views: 110

Answers (2)

Sundeep
Sundeep

Reputation: 23677

With GNU sed

$ line='i_ref_clk i_ref_clk i_ait_rstn i_ait_rstn abc def def'
$ echo "$line" | sed -E 's|\b(\w+)\b(.*)\b\1\b|\1\2kiran/\1|g'
i_ref_clk kiran/i_ref_clk i_ait_rstn kiran/i_ait_rstn abc def kiran/def
  • \b(\w+)\b capture a whole word (\b are word boundaries and \w matches any word character)
  • (.*) any number of characters
  • \b\1\b match same whole word as matched by first capture group
  • \1\2kiran/\1 in replacement section, add text as required
  • note that | is used as delimiter assuming it wouldn't conflict with input characters and assumes that a word is repeated only twice

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133650

Could you please try following, if you are ok with awk.

awk -v var="kiran/" '{for(i=1;i<=NF;i++){if(++a[$i]==2){$i=var $i}};delete a} 1' Input_file

Or adding a non-one liner form of above solution:

awk -v var="kiran/" '
{
  for(i=1;i<=NF;i++){
    if(++a[$i]==2){
      $i=var $i
    }
  }
  delete a
}
1
'   Input_file

Output for shown sample will be as follows.

i_ref_clk kiran/i_ref_clk i_ait_rstn kiran/i_ait_rstn abc kiran/def

Upvotes: 2

Related Questions