Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

input.txt

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.

output.txt

Nucus_2158_mri_1/2_Co_1.0_Le_3104 EN1,EN3,EN5
share|improve this question
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
add comment

2 Answers

up vote 2 down vote accepted

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
  else
    H[$2] = H[$2]","$1
}
END {
  for(key in H)
    print key, H[key]
}' infile

Output:

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
share|improve this answer
add comment

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'
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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