I have tab-delimited text file containing about more than 1500 rows.


id   sno1   
EN1  Nucus_2158_mri_1/2_Co_1.0_Le_3104
EN2  Nucus_2158_mri_4/2_Co_1.0_Le_3104
EN3  Nucus_2158_mri_1/2_Co_1.0_Le_3104
EN4  Nucus_2158_mri_1/2_Co_1.0_Le_3106
EN5  Nucus_2158_mri_1/2_Co_1.0_Le_3104
EN6  Nucus_2159_mri_1/2_Co_1.0_Le_3104

I want to get exact match within column (sno1) by capturing bracketed values (Nucus_{2158}_mri_{1/2}_Co_1.0_Le_{3104}) and print their matching ids list. Any help in awk/sed appreciated.


Nucus_2158_mri_1/2_Co_1.0_Le_3104 EN1,EN3,EN5
  • 2
    Can you what you mean by the dollar signs better? Usually the best way to explain such things is: (1) illustrative sample input (2) sample command (3) expected output. You've got 1 and 3 but are a bit unclear on (2). – jw013 Jul 27 '12 at 22:47
  • Shouldn't EN2 be part of the matched list? – Thor Jul 27 '12 at 23:04
  • @Thor: no, because it's mri_4, not mri_1 (at least, if I understand correctly). – bahamat Jul 27 '12 at 23:39
  • Ah, I missed the middle pair of dollar signs. – Thor Jul 27 '12 at 23:53

Assuming you mean the whole second element is the same in each case, you can use it as the key in an associative array. Here is an awk example that relies on that:

awk '
/^EN/ {
  if(H[$2] == "")
    H[$2] = $1
    H[$2] = H[$2]","$1
  for(key in H)
    print key, H[key]
}' infile


Nucus_2158_mri_4/2_Co_1.0_Le_3104 EN2
Nucus_2159_mri_1/2_Co_1.0_Le_3104 EN6
Nucus_2158_mri_1/2_Co_1.0_Le_3104 EN1,EN3,EN5
Nucus_2158_mri_1/2_Co_1.0_Le_3106 EN4
|improve this answer|||||

pass in the three keys using awk command-line variables(named first, second and third in the example below)

awk -v first=2158 -v second=1/2 -v third=3104 
'$2 == "Nucus_"first"_mri_"second"_Co_1.0_Le_"third{print($2,$1)}' input.txt      
| awk '{deleter=$1; gsub(deleter, "", $0);} NR != 1 {deleter=""}{print(deleter" "$0)}' 
| sed -e 's/^\s\+//g' | sed ':a;N;$!ba;s/\n/,/g'
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.