Skip to content

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.

Advertisement

Answer

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