How do I remove allele annotations from SNP Ids in .bim file?

Hello every one i need help in editting my .bim file. So my .bim file looked like following. I want to convert the ids with chromosomal position from chr1_867635_C_T to chr1_867635 while others remained as it is. I want to remove all the alleles from my SNP IDs, not just specific ones.

1       rs2880024             866893  A       G
1       chr1_867635_C_T       867635  A       G
1       chr1_869303_C_T       869303  A       G
1       chr1_873558_G_T       873558  C       A
1       exm2275405           879439  A       G


The simplest approach is to remove the first occurrence of a _ followed by a capital letter, another _ and another capital letter from each line:

$sed 's/_[A-Z]_[A-Z]//' file 1 rs2880024 866893 A G 1 chr1_867635 867635 A G 1 chr1_869303 869303 A G 1 chr1_873558 873558 C A 1 exm2275405 879439 A G  Alternatively, find the first occurrence of chr followed by numbers, then an underscore and more numbers and remove all non-whitespace characters after the last numbers (note that this assumes GNU sed, the default on Linux systems): $ sed -E 's/(\schr[0-9]+_[0-9]+)_\S+/\1/' file
1       rs2880024             866893  A       G
1       chr1_867635       867635  A       G
1       chr1_869303       869303  A       G
1       chr1_873558       873558  C       A
1       exm2275405           879439  A       G


If your file is more varied than you show, you can use this to ensure you only make the change on the 2nd field:

$awk -F'[ ]' '{ sub(/_[A-Z]_[A-Z]/,"",$2)}1' file
1       rs2880024             866893  A       G
1       chr1_867635_C_T       867635  A       G
1       chr1_869303_C_T       869303  A       G
1       chr1_873558_G_T       873558  C       A
1       exm2275405           879439  A       G


Or, the same but only matching A, C, T or G:

$awk -F'[ ]' '{ sub(/_[ACTG]_[ACTG]/,"",$2)}1' file
1       rs2880024             866893  A       G
1       chr1_867635_C_T       867635  A       G
1       chr1_869303_C_T       869303  A       G
1       chr1_873558_G_T       873558  C       A
1       exm2275405           879439  A       G

• The output of these commands should be piped out to another file (e.g. using >)
– gringer
Jun 10 '21 at 12:19
• Yep. Either that, or add an -i to the sed commands and a -i inplace to the awk (assuming GNU awk) commands to edit the file in place. Jun 10 '21 at 12:20