I’m trying to replace every second instance word of each line with sed
.
For example: If I had a line as below
JavaScript
x
i_ref_clk i_ref_clk i_ait_rstn i_ait_rstn abc kiran/def
should be replaced as below.
JavaScript
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 :
JavaScript
echo " i_ref_clk i_ref_clk i_ait_rstn i_ait_rstn abc def def" | sed 's/ / kiran//2'
Output:
JavaScript
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
.
JavaScript
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:
JavaScript
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.
JavaScript
i_ref_clk kiran/i_ref_clk i_ait_rstn kiran/i_ait_rstn abc kiran/def