Extraire un champ d'un fichier
RésoluBonjour,
J'ai un fichier qui possède plusieurs champs commençant par "#?BEGIN" et finissant par "#?END".
Ce champ compte une vingtaine de lignes.
Dans ces différents champs, j'ai une information qui revient régulièrement et qui se présente sous cette forme : sc_objet_name=toto
En s'appuyant sur cette information, j'aurais besoin de récupérer l'intégralité du champs associé.
Je suis sur un système linux et pour l'instant je n'ai pas encore réussi à trouver comment procéder pour récupérer ces informations.
J'en appelle donc à votre aide.
Voici un exemple du fichier qui doit faire l'objet de l'extraction (pour plus de clarté):
a_sentinel_transfer_filter='UNDEFINED' a_attach_extract_file='U' a_generate_xfb_subject='U' #?END_APPLI #?BEGIN sc_objet_name='00SUCNAP' a_group='GDEFAULT' a_direction_allowed='I' a_comments='RAS' a_rec_len='32768' a_data_code='B' a_x_file_org='S' a_x_rec_fmt='V' a_x_rec_len='32768' a_x_data_code='A' a_padding='00' a_truncating_allowed='N' a_file_dispo='undefined' a_file_action='undefined' a_check_records='N' a_block_size='4096' a_sys_dep='' a_text_file='N' a_dir_path='/depot1/pesit/prod/toto' a_file_component='&(x_appli).&(x_xfer_ident)_&(x_local_ident)' #?END #?BEGIN_APPLI sc_objet_name='00SUCNAT' a_group='GDEFAULT'
Merci d'avance pour votre aide.
9 réponses
Extraction des blocs délimités par #?BEGIN et #?END dans un fichier contenant une ligne sc_objet_name, afin de récupérer celui correspondant à un nom donné sur Linux. Des contributions suggèrent d'employer sed ou awk pour parcourir le fichier et isoler le bloc où la ligne sc_objet_name correspond au nom recherché, tout en distinguant BEGIN_APPLI et END_APPLI le cas échéant. Plusieurs échanges mentionnent des difficultés liées à l'expansion des variables ou à l'exécution multi-ligne dans les scripts, et des vérifications pratiques autour des exemples comme 00SUCNAP. Une nuance utile consiste à vérifier que BEGIN et END englobent bien la ligne sc_objet_name et à extraire le bloc correspondant pour une réutilisation dans des pipelines ou scripts.
-
Modérateurcat 'fichier' |grep sc_objet_name |awk -F"=" '{print $2}'
avec le fichier que tu as donné, tu auras en résultat :
'00SUCNAP'
'00SUCNAT'
tu peux faire sauter les ' avec un deuxieme awk : awk -F"'" '{print $2}'
(après le -F c'est guilllemets(touche3) - apostrophe simple(touche4) - guillemets - espace - apostrophe simple - accolade ouvrante)
Stop failing the turing test ! -
Merci pour ta réponse dna.factory, mais en fait il faut que la commande me donne le résultat suivant :
#?BEGIN
sc_objet_name='00SUCNAP'
a_group='GDEFAULT'
a_direction_allowed='I'
a_comments='RAS'
a_rec_len='32768'
a_data_code='B'
a_x_file_org='S'
a_x_rec_fmt='V'
a_x_rec_len='32768'
a_x_data_code='A'
a_padding='00'
a_truncating_allowed='N'
a_file_dispo='undefined'
a_file_action='undefined'
a_check_records='N'
a_block_size='4096'
a_sys_dep=''
a_text_file='N'
a_dir_path='/depot1/pesit/prod/toto'
a_file_component='&(x_appli).&(x_xfer_ident)_&(x_local_ident)'
#?END
C'est donc le champs à partir de "#?BEGIN" jusqu'à "#?END" que je dois récupérer... -
Modérateurah oui, tout de suite plus intéressant...
je reste persuadé que le salut viendra de awk ou de sed
je regarde de mon coté (ça m'intéressera aussi de toute façon)
juste pour être sur : c'est bien de la prod (tout les coups sont permis) et pas un exercice scolaire avec une contrainte d'execution ?
(je pense entre autre aux fichiers temporaires) -
Oui c'est bien de la production.
Cette commande est censée terminer un script que je développe depuis quelques jours. Mais là, je suis totalement bloqué. Misère ! -
ContributeurSalut,
Pour résumer...
Tu ne dois récupérer l'intervalle "#?BEGIN => #?END" que si celui-ci contient bien une ligne "sc_objet_name='xxxx'", c'est ça ?
-
Salut Zipe31,
Oui car chaque champs "#?BEGIN => #?END" comporte systématiquement l'information "sc_objet_name='xxxx'".
Par ailleurs, l'extraction du champs doit se faire à partir de cette données (par un grep où autres...)
Merci.-
-
-
-
Voici un extrait du fichier original (la capture ci-dessous a été extraite en plein milieu du fichier):
......
a_sentinel_transfer_filter='UNDEFINED'
a_attach_extract_file='U'
a_generate_xfb_subject='U'
#?END_APPLI
#?BEGIN
sc_objet_name='00SUCNAP'
a_group='GDEFAULT'
a_direction_allowed='I'
a_comments='RAS'
a_rec_len='32768'
a_data_code='B'
a_x_file_org='S'
a_x_rec_fmt='V'
a_x_rec_len='32768'
a_x_data_code='A'
a_padding='00'
a_truncating_allowed='N'
a_file_dispo='undefined'
a_file_action='undefined'
a_check_records='N'
a_block_size='4096'
a_sys_dep=''
a_text_file='N'
a_dir_path='/depot1/pesit/prod/toto'
a_file_component='&(x_appli).&(x_xfer_ident)_&(x_local_ident)'
#?END
#?BEGIN_APPLI
sc_objet_name='00SUCNAT'
a_group='GDEFAULT'
etc.....
Maintenant si je me fixe sur l'information '00SUCNAP' qui se trouve devant "sc_objet_name=", je dois obtenir au final, le résultat suivant :
#?BEGIN
sc_objet_name='00SUCNAP'
a_group='GDEFAULT'
a_direction_allowed='I'
a_comments='RAS'
a_rec_len='32768'
a_data_code='B'
a_x_file_org='S'
a_x_rec_fmt='V'
a_x_rec_len='32768'
a_x_data_code='A'
a_padding='00'
a_truncating_allowed='N'
a_file_dispo='undefined'
a_file_action='undefined'
a_check_records='N'
a_block_size='4096'
a_sys_dep=''
a_text_file='N'
a_dir_path='/depot1/pesit/prod/toto'
a_file_component='&(x_appli).&(x_xfer_ident)_&(x_local_ident)'
#?END
Est-ce que ça te parait plus clair ?
Merci en tout cas pour ton aide. -
ContributeurOui et non ;-\
Non parce que la commande que je t'ai donnée précédemment fait ce que tu demandes ;-\
Non parce que tu ne donnes qu'un exemple où se trouve qu'UN seul exemple d'intervalle "BEGIN => END" ;-(
Pour te montrer ma bonne foi :
Que je lance ma commande précédente :sed -n '/#\?BEGIN$/,/#\?END$/p' fichier
ou une vérifiant si la ligne "sc_objet_name" existe bien dans l'intervalle :sed -n '/#\?BEGIN$/{:z;N;/#\?END$/! bz;/sc_objet_name/p}' fichier
J'obtiens le même résultat ;-\
-
-
Modérateurune première idée :
extraire systématiquement les chaines de begin à end dans un fichier temporaire,
une fois que c'est fait tester le fichier temporaire, et si y'a pas l'info, le rejeter et continuer....
pas besoin de awk ou de sed, mais beaucoup de boucles imbriquées et probablement des breaks/exits -
Modérateur
Une méthode très sale... je suis même pas sûr que ça marche...
- Tu définis une variable fichier=/dev/null
- Tu boucles sur toutes les lignes de ton fichier et dans cette boucle tu fais
- Si la ligne contient begin, alors fichier= ton fichier
- Si la ligne contient end, alors fichier = /dev/null
- Dans tous les cas, tu envoie la ligne dans $fichier
et le pire... même pas honte.
--
Stop failing the turing test ! -
Modérateur
Bonjour,
Le sujet est vieux mais comme on n'y a jamais répondu complètement et que ce brave bobot l'a fait remonté, voici une solution possible en python3.Pour rappel, sous Linux, python3 s'installe via le gestionnaire de paquets (par exemple APT sous Debian ou Ubuntu) :
sudo apt update sudo apt install python3
Ensuite on crée le fichier suivant (appelons-le script.py)
import sys from io import StringIO, TextIOBase from pprint import pprint KEY_FIELD = "sc_objet_name" def autocast(s: str): for t in (int, float): try: return t(s) except ValueError, TypeError: continue return s class Data(dict): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.current_key = None self.current_dict = None def process_line(self, line: str): line = line.strip() if line in {"#?BEGIN", "#?BEGIN_APPLI"}: print(f"--- begin {line=}") self.current_dict = dict() elif line in {"#?END", "#?END_APPLI"}: print(f"--- end {line=}") if self.current_dict is None: print(f"!!! {self.current_dict=}: Not set. Trailing data?") else: key = self.current_dict.get(KEY_FIELD) if key is None: print(f"!!! {self.current_dict=}: No '{KEY_FIELD}' key") elif key in self: print(f"!!! {self.current_dict=}: {key=} is already registered!") else: self[key] = self.current_dict self.current_dict = None elif line: print(f"--- line {line=}") if self.current_dict is not None: (key, value) = line.split("=") value = autocast(value.strip("'")) self.current_dict[key] = autocast(value) else: print(f"!!! Dictionnary not yet set") @classmethod def from_stream(cls: type, stream: TextIOBase) -> Data: ret = cls() for line in stream.readlines(): ret.process_line(line) return ret def test_data_stringio(): stream = StringIO(""" a_sentinel_transfer_filter='UNDEFINED' a_attach_extract_file='U' a_generate_xfb_subject='U' #?END_APPLI #?BEGIN sc_objet_name='00SUCNAP' a_group='GDEFAULT' a_direction_allowed='I' a_comments='RAS' a_rec_len='32768' a_data_code='B' a_x_file_org='S' a_x_rec_fmt='V' a_x_rec_len='32768' a_x_data_code='A' a_padding='00' a_truncating_allowed='N' a_file_dispo='undefined' a_file_action='undefined' a_check_records='N' a_block_size='4096' a_sys_dep='' a_text_file='N' a_dir_path='/depot1/pesit/prod/toto' a_file_component='&(x_appli).&(x_xfer_ident)_&(x_local_ident)' #?END #?BEGIN_APPLI sc_objet_name='00SUCNAT' a_group='GDEFAULT' #?END_APPLI""") data = Data.from_stream(stream) print("---> Whole data structure") pprint(data) print("---> Whole 00SUCNAP object") pprint(data["00SUCNAP"]) print("---> 00SUCNAP object, a_dir_path attribute") pprint(data["00SUCNAP"]["a_dir_path"]) if len(sys.argv) > 1: with open(sys.argv[1]) as f: data = Data.from_stream(f) pprint(data) else: print("Running tests") test_data_stringio()Quelques explications :
- Data est l'objet qui va organiser les données lues depuis un flux d'entrée (stream en anglais), provenant soit d'une chaîne de caractère (StringIO), soit d'un fichier. Puis on lit le flux ligne par ligne.
- Si la ligne est dans l'ensemble {"#?BEGIN", "#?BEGIN_APPLI"}, on commence à créer un nouveau dictionnaire (= ensemble de paires clé-valeur).
- Si la ligne est dans l'ensemble {"#?END", "#?END_APPLI"}, on considère que le dictionnaire en court de construction est maintenant terminé, et on l'enregistre dans Data, à la clé définie par le champ "sc_objet_name".
- Sinon, on décompose la ligne par rapport au caractère "=" : de part et d'autre on définit une paire clé-valeur à ajouter au dictionnaire en court de construction.
- Le reste du script gère les cas d'erreurs, dans le cas où le flux d'entrée est mal formé (ce qui est le cas de l'exemple).
On sauve et quitte. On peut mettre des droits en exécution au script (cela permettra de l'appeler directement, sans invoquer explicitement l'interpréteur python)
chmod a+x script.py
On crée un fichier de donnée (appelons-le data.txt)
a_sentinel_transfer_filter='UNDEFINED' a_attach_extract_file='U' a_generate_xfb_subject='U' #?END_APPLI #?BEGIN sc_objet_name='00SUCNAP' a_group='GDEFAULT' a_direction_allowed='I' a_comments='RAS' a_rec_len='32768' a_data_code='B' a_x_file_org='S' a_x_rec_fmt='V' a_x_rec_len='32768' a_x_data_code='A' a_padding='00' a_truncating_allowed='N' a_file_dispo='undefined' a_file_action='undefined' a_check_records='N' a_block_size='4096' a_sys_dep='' a_text_file='N' a_dir_path='/depot1/pesit/prod/toto' a_file_component='&(x_appli).&(x_xfer_ident)_&(x_local_ident)' #?END #?BEGIN_APPLI sc_objet_name='00SUCNAT' a_group='GDEFAULT' #?END_APPLI
Pour utiliser le script. Il y a deux manières de le lancer, soit en explicitant l'interpréteur, soit en le sous-entendant (sous réserve que le chmod a été fait). Ici j'ai écrit le script pour que si aucun argument n'est passé en ligne de commande, il exécute la fonction de test. On peut donc lancer le script ainsi :
./script.py python3 script.py
Résultat obtenu :
Running tests --- line line="a_sentinel_transfer_filter='UNDEFINED'" !!! Dictionnary not yet set --- line line="a_attach_extract_file='U'" !!! Dictionnary not yet set --- line line="a_generate_xfb_subject='U'" !!! Dictionnary not yet set --- end line='#?END_APPLI' !!! self.current_dict=None: Not set. Trailing data? --- begin line='#?BEGIN' --- line line="sc_objet_name='00SUCNAP'" --- line line="a_group='GDEFAULT'" --- line line="a_direction_allowed='I'" --- line line="a_comments='RAS'" --- line line="a_rec_len='32768'" --- line line="a_data_code='B'" --- line line="a_x_file_org='S'" --- line line="a_x_rec_fmt='V'" --- line line="a_x_rec_len='32768'" --- line line="a_x_data_code='A'" --- line line="a_padding='00'" --- line line="a_truncating_allowed='N'" --- line line="a_file_dispo='undefined'" --- line line="a_file_action='undefined'" --- line line="a_check_records='N'" --- line line="a_block_size='4096'" --- line line="a_sys_dep=''" --- line line="a_text_file='N'" --- line line="a_dir_path='/depot1/pesit/prod/toto'" --- line line="a_file_component='&(x_appli).&(x_xfer_ident)_&(x_local_ident)'" --- end line='#?END' --- begin line='#?BEGIN_APPLI' --- line line="sc_objet_name='00SUCNAT'" --- line line="a_group='GDEFAULT'" --- end line='#?END_APPLI' ---> Whole data structure {'00SUCNAP': {'a_block_size': 4096, 'a_check_records': 'N', 'a_comments': 'RAS', 'a_data_code': 'B', 'a_dir_path': '/depot1/pesit/prod/toto', 'a_direction_allowed': 'I', 'a_file_action': 'undefined', 'a_file_component': '&(x_appli).&(x_xfer_ident)_&(x_local_ident)', 'a_file_dispo': 'undefined', 'a_group': 'GDEFAULT', 'a_padding': 0, 'a_rec_len': 32768, 'a_sys_dep': '', 'a_text_file': 'N', 'a_truncating_allowed': 'N', 'a_x_data_code': 'A', 'a_x_file_org': 'S', 'a_x_rec_fmt': 'V', 'a_x_rec_len': 32768, 'sc_objet_name': '00SUCNAP'}, '00SUCNAT': {'a_group': 'GDEFAULT', 'sc_objet_name': '00SUCNAT'}} ---> Whole 00SUCNAP object {'a_block_size': 4096, 'a_check_records': 'N', 'a_comments': 'RAS', 'a_data_code': 'B', 'a_dir_path': '/depot1/pesit/prod/toto', 'a_direction_allowed': 'I', 'a_file_action': 'undefined', 'a_file_component': '&(x_appli).&(x_xfer_ident)_&(x_local_ident)', 'a_file_dispo': 'undefined', 'a_group': 'GDEFAULT', 'a_padding': 0, 'a_rec_len': 32768, 'a_sys_dep': '', 'a_text_file': 'N', 'a_truncating_allowed': 'N', 'a_x_data_code': 'A', 'a_x_file_org': 'S', 'a_x_rec_fmt': 'V', 'a_x_rec_len': 32768, 'sc_objet_name': '00SUCNAP'} ---> 00SUCNAP object, a_dir_path attribute '/depot1/pesit/prod/totoOn observe qu'on a bien enregistré dans notre instance "data" de type "Data" deux clés (00SUCNAP et 00SUCNAT). Comme le montre la fonction de test, on peut facilement extraire les objets ou champs d'objet qui nous intéressent.
Si on veut passer que le fichier à traiter soit passé en paramètre :
./script.py data.txt python3 script.py data.txt
Résultat obtenu :
--- line line="a_sentinel_transfer_filter='UNDEFINED'" !!! Dictionnary not yet set --- line line="a_attach_extract_file='U'" !!! Dictionnary not yet set --- line line="a_generate_xfb_subject='U'" !!! Dictionnary not yet set --- end line='#?END_APPLI' !!! self.current_dict=None: Not set. Trailing data? --- begin line='#?BEGIN' --- line line="sc_objet_name='00SUCNAP'" --- line line="a_group='GDEFAULT'" --- line line="a_direction_allowed='I'" --- line line="a_comments='RAS'" --- line line="a_rec_len='32768'" --- line line="a_data_code='B'" --- line line="a_x_file_org='S'" --- line line="a_x_rec_fmt='V'" --- line line="a_x_rec_len='32768'" --- line line="a_x_data_code='A'" --- line line="a_padding='00'" --- line line="a_truncating_allowed='N'" --- line line="a_file_dispo='undefined'" --- line line="a_file_action='undefined'" --- line line="a_check_records='N'" --- line line="a_block_size='4096'" --- line line="a_sys_dep=''" --- line line="a_text_file='N'" --- line line="a_dir_path='/depot1/pesit/prod/toto'" --- line line="a_file_component='&(x_appli).&(x_xfer_ident)_&(x_local_ident)'" --- end line='#?END' --- begin line='#?BEGIN_APPLI' --- line line="sc_objet_name='00SUCNAT'" --- line line="a_group='GDEFAULT'" --- end line='#?END_APPLI' {'00SUCNAP': {'a_block_size': 4096, 'a_check_records': 'N', 'a_comments': 'RAS', 'a_data_code': 'B', 'a_dir_path': '/depot1/pesit/prod/toto', 'a_direction_allowed': 'I', 'a_file_action': 'undefined', 'a_file_component': '&(x_appli).&(x_xfer_ident)_&(x_local_ident)', 'a_file_dispo': 'undefined', 'a_group': 'GDEFAULT', 'a_padding': 0, 'a_rec_len': 32768, 'a_sys_dep': '', 'a_text_file': 'N', 'a_truncating_allowed': 'N', 'a_x_data_code': 'A', 'a_x_file_org': 'S', 'a_x_rec_fmt': 'V', 'a_x_rec_len': 32768, 'sc_objet_name': '00SUCNAP'}, '00SUCNAT': {'a_group': 'GDEFAULT', 'sc_objet_name': '00SUCNAT'}}Bonne chance