I have some files contained identifiers as below:
B#205918
A#273075
E#554065
Eg. sample of file1:
((((A#273075,A#273116),((A#224325,A#192952),A#243232)),(((E#7955,E#7165),E#6239),E#4530)),(((((E#3075,E#3702),B#251221),E#35128),B#243275),((B#198094,B#176280),B#273119)))
In this file, the identifiers only began from three alphabets (clusters); A/B/E. I would want to automate the extraction the identifiers that starts with A/B/E into separate files, where each file contain identifiers of those in the same cluster only.
The identifiers within the same bracket belongs to the same group. For example, ((B#198094,B#176280),B#273119)
B#198094 and B#196280 are within the same inner group, and together with B#273119, three of them are within the bigger group. That said, the brackets do matter during the extraction of the identifiers.
Basically what I can picture on the algorithm is to extract the identifiers and all the matching open & close brackets that enclosed them, when all the identifiers within the brackets start with those in same cluster (either A/B/E).
Expected output files:
cluster A:
((A#273075,A#273116),((A#224325,A#192952),A#243232))
cluster B:
((B#198094,B#176280),B#273119)
cluster E*:
(((E#7955,E#7165),E#6239),E#4530)
(E#3075,E#3702)
*It can be more than a single line in the extraction output files as there are possibilities for the identifiers of the same cluster not being placed in the same group (the outlier) -- It can be seen in the sample file that the two groups of identifiers in cluster E file were not enclosed by any common bracket, except the brackets that enclosed all the identifiers.
This is what I have got so far for cluster A extraction:
grep -o "(*(A#.*)*" file1 | sed 's/,*E#.*//g'
but this doesn't applies to clusters that appear more than once in different part of the file, i.e. cluster E in this case. Also, it wasn't actually focus on the number of brackets being extracted, which will cause error on the output file (the number of open brackets and close brackets are different).
sed
and perl
command doesn't work for me. I tried splitting the file at each comma and extract each subsequent line start with E (to extract the E cluster).
sed 's/,/,\n/g' file1 | sed -n '/*E.*,\n(E/p'
sed -n ':begin;$!N;/*(E#.*\n*(E/p' file1
sed 's/,/,\n/g' file1 | perl -ane 'if(/.*E#.,\n*E#./ ... /^}/){$counter++ if /\(E#/; print if $counter==1}'
I am a bit lost in the process and trying hard to emphasis this in the simplest and shortest way possible. Do let me know if there's anything missed out or part that is less clear.
awk
has no lookahead/behind expressions. You'd have to count parentheses and write a lot of stuff. This fits to perl, python etc.