2011-09-30 6 views
0

Je ne connais pas bien les scripts bash et j'ai du mal à comprendre ce problème. J'ai environ deux cents fichiers qui suivent ce modèle:Lire un fichier et stocker des valeurs arbitraires dans une variable dans le script bash

ANÁLISE DA GLOSA FUNGICIDA 
A ANÁLISE RESULTA EM: 
S='Glosa02626354' = "agente que destrói ou previne o crescimento de fungos" 
    {antifúngico: O I]antifúngico clássico utilizado no tratamento não previne a disseminação típica da infecção., 
    agente antifúngico: Os resultados sugerem a utilização terapêutica do extrato do limão como I]agente antifúngico na Odontologia., 
    fungicida: A duração do ]fungicida no carpete tem garantia de cinco anos., 
    antimicótico: Os grupos nomearam o I]antimicótico e realizaram campanha de lançamento fictícia, com material técnico de divulgação e brindes., 
    agente antimicótico: Em caso de infecção, deverá ser instituído o uso de um I]agente antimicótico.} 

Chave: FUNGICIDA <noun.artifact> 
ILI: 02626354 
Sense 1 
{02626354} <noun.artifact> antifungal, antifungal agent, fungicide, antimycotic, antimycotic agent -- (any agent that destroys or prevents the growth of fungi) 
     => {13935705} <noun.substance> agent -- (a substance that exerts some force or effect) 
      => {00005598} <noun.Tops> causal agent, cause, causal agency -- (any entity that causes events to happen) 
       => {00001740} <noun.Tops> entity -- (that which is perceived or known or inferred to have its own distinct existence (living or nonliving)) 

Dans ce cas, je dois stocker les valeurs suivantes entre accolades: « antifúngico », « agente antifúngico », « fungicida », « antimicótico » et ' agente antimicótico 'dans une variable. Ces mots seront bien entendu différents dans chaque dossier. A titre de comparaison, voici un autre fichier:

ANÁLISE DA GLOSA VIA ÁPIA 
A ANÁLISE RESULTA EM: 
S='Glosa02634922' = "estrada da antiga Roma, na Itália, extendendo-se ao sul, de Roma a Brindisi; iniciada em 312 AC" 
    {Via Ápia: Toda a I]Via Apia era conhecida quer pela sua extensão, quer pela sua extraordinária beleza.} 

Chave: VIA ÁPIA <noun.artifact> 
ILI: 02634922 
Sense 1 
{02634922} <noun.artifact> Appian Way#1 -- (an ancient Roman road in Italy extending south from Rome to Brindisi; begun in 312 BC) 
     => {03390668} <noun.artifact> highway#1, main road#1 -- (a major road for any form of motor transport) 
      => {03941718} <noun.artifact> road#1, route#2 -- (an open way (generally public) for travel or transportation) 
       => {04387207} <noun.artifact> way#6 -- (any artifact consisting of a road or path affording passage from one place to another; "he said he was looking for the way out") 
        => {00019244} <noun.Tops> artifact#1, artefact#1 -- (a man-made object taken as a whole) 
         => {00016236} <noun.Tops> object#1, physical object#1 -- (a tangible and visible entity; an entity that can cast a shadow; "it was full of rackets, balls and other objects") 
          => {00001740} <noun.Tops> entity#1 -- (that which is perceived or known or inferred to have its own distinct existence (living or nonliving)) 
         => {00002645} <noun.Tops> whole#2, whole thing#1, unit#6 -- (an assemblage of parts that is regarded as a single entity; "how big is that part compared to the whole?"; "the team is a unit") 
          => {00016236} <noun.Tops> object#1, physical object#1 -- (a tangible and visible entity; an entity that can cast a shadow; "it was full of rackets, balls and other objects") 
           => {00001740} <noun.Tops> entity#1 -- (that which is perceived or known or inferred to have its own distinct existence (living or nonliving)) 

Ici, la variable aura une seule valeur, la chaîne 'Via Ápia'.


Mise à jour: J'ai trouvé un moyen de distinguer les lignes qui sont pertinentes en utilisant une magie d'expression régulière:

grep ':*\.,' file_name.txt 

La sortie de cette commande pour le premier exemple est

{antifúngico: O I]antifúngico clássico utilizado no tratamento não previne a disseminação típica da infecção., 
    agente antifúngico: Os resultados sugerem a utilização terapêutica do extrato do limão como I]agente antifúngico na Odontologia., 
    fungicida: A duração do ]fungicida no carpete tem garantia de cinco anos., 
    antimicótico: Os grupos nomearam o I]antimicótico e realizaram campanha de lançamento fictícia, com material técnico de divulgação e brindes., 
+0

pouvez-vous donner un exemple concret? Il me semble que quelque chose comme ça: 'x = $ (cat fichier | grep )' fonctionnera mais il est difficile de dire sur la base du manque de détails dans votre question. – Kevin

+0

@Kevin, je mets de vrais exemples, tirés des fichiers. J'ai d'abord pensé que mettre tout le contenu serait trop chaotique. – rberaldo

+0

@rberaldo Je pense avoir compris ce que tu veux. Pouvez-vous ajouter un exemple (réel) du format de sortie souhaité? De plus, la première définition a-t-elle vraiment des symboles '' {'' et ''] ''? –

Répondre

0

Si vous voulez juste assigner le résultat de votre correspondance regex à une variable dans bash, alors ceci devrait le faire:

myVar=$(cat file_name.txt|grep ':*\.,') 

EDIT:

Cela peut vous obtenir un peu plus près:

myVar=$(cat file_name.txt|grep ':*\.,'|./x.pl) 

Où x.pl est:

#!/usr/bin/perl 

while (<STDIN>) { 
    my @x = split /,/; 

    foreach (@x) { 
     print $1 . "\n" if /\{?\W*(.*?)\:/; 
    } 
} 

qui va extraire les 4 mots que vous voulez, séparés par newlines. Je ne sais toujours pas si c'est ce que tu veux.

+0

Cela me donne presque ce que je veux. Ma variable ne devrait avoir que le contenu avant les deux points. – rberaldo

+0

Je viens de copier l'expression régulière de votre question ... n'est-ce pas ce que vous voulez? – Kevin

+0

Non, j'ai juste besoin de quelques-uns des mots de ces lignes, plus précisément les mots qui viennent _before_ le colon dans chaque ligne. Dans l'exemple que j'ai donné, j'ai juste besoin des mots «antifúngico», «agente antifúngico», «fungicida» et «antimicótico». – rberaldo

0

Si vous avez GNU grep, vous pouvez avoir une bonne chance avec grep -Po '(?<={)[^:]+(?=:)'

Questions connexes