**We have talked about quite a few things in our CnC articles so far. However, there is one, even I struggle with sometimes, mainly because I don’t get to use it often. So as a refresher, let’s talk about grep. As an Ubuntu newbie, it will not be high on your priority list, however, it is something you will use if you ever work in an environment that is Linux-based. Even if you never do, it is a rather weird thing to master. When you use it, to untrained eyes, it will seem like magic. Let's start with the syntax, in other words, how we use it. It is as follows: grep file; grep filename; command | grep So it’s not difficult to grasp and the man page says this about it: grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command.** Nous avons abordé plusieurs points dans nos articles de C&C jusqu'à présent. Cependant, il y en a un avec lequel j'ai parfois du mal, principalement parce que je ne l'utilise pas souvent. Pour rappel, parlons de grep. En tant que débutant sous Ubuntu, ce ne sera pas une priorité pour vous, mais vous l'utiliserez si vous travaillez un jour dans un environnement Linux. Même si vous ne l'utilisez jamais, c'est une fonction assez complexe à maîtriser. Pour un œil non averti, cela semblera magique. Commençons par la syntaxe, autrement dit, son utilisation. La voici : grep fichier ; grep nom_fichier ; commande | grep Ce n'est donc pas difficile à comprendre, et la page de manuel le précise : grep recherche des MOTIFS dans chaque FICHIER. Les MOTIFS sont un ou plusieurs motifs séparés par des sauts de ligne, et grep affiche chaque ligne correspondant au motif. En règle générale, les MOTIFS doivent être entre guillemets lorsque grep est utilisé dans une commande shell. **Let’s start simple, let’s look for a “word” (pattern) in a file. Here is my query: grep distro /home/edd/dotfile.txt Broken down, search for the pattern “distro” inside the file at this location and we can see it in action: Let’s now take the output of a file and pipe it into grep to filter it. Here is my query: inxi -G | grep resolution Broken down, run inxi, filter it by graphics and then pipe it to grep, isolating my pattern, namely resolution Great, I’m sure we are all on the same page, so far. This is the very basics of finding your pattern. A lot of people will say “word” when showing you how to use grep, but you could type “reso” instead of “resolution”, it does not need to be a “word”. ** Commençons simplement : recherchons un « mot » (motif) dans un fichier. Voici ma requête : grep distro /home/edd/dotfile.txt En détail, recherchez l'emplacement du motif « distro » dans le fichier ; nous pouvons le voir en action : Prenons maintenant la sortie d’un fichier et envoyons-la dans grep pour la filtrer. Voici ma requête : inxi -G | grep resolution En détail, lancez inxi, filtrez par « graphics » (-G), puis envoyez-la vers grep pour isoler mon motif, à savoir « resolution ». Super, je suis sûr que nous sommes tous sur la même longueur d’onde jusqu’ici. Voici les bases pour trouver votre motif. Beaucoup de gens diront « mot » lorsqu’ils vous montreront comment utiliser grep, mais vous pouvez saisir « reso » au lieu de « résolution » ; ce n’est pas forcément un « mot ». **Helpful hint no. 1: You can use the case insensitive flag if you want, say, VGA as well as vga. I use it mechanically, I had to reshoot these screen-shots, as they had the -i in default. (not that it made a big difference, but I’d rather not confuse newbies.) The next most helpful way of finding things is via recursive searching. Here is my query: grep -r "lists.ubuntu.com" /home/edd/Documents/FCM25/Weekly\ news/ Broken down, search for my pattern in a directory (how many times I have cited lists.ubuntu.com as a source) . We can also use -R here. So now our output is slightly different. I have the full pathname of the file, followed by a :-> (which is not a smiley in this case) and followed by the instances where they were found. Note: I cannot just do this: grep "lists.ubuntu.com" /home/edd/Documents/FCM25/Weekly\ news/ - as the target of my search is a folder, not a file. ** Conseil pratique n° 1 : Vous pouvez utiliser l’option « insensible à la casse » (-i) si vous souhaitez, par exemple, utiliser VGA ou vga. Je l’utilise mécaniquement ; j’ai dû refaire ces captures d’écran, car elles avaient l’option -i par défaut. (Ce n’est pas vraiment important, mais je préfère ne pas embrouiller les débutants.) La méthode la plus efficace pour trouver des informations est la recherche récursive. Voici ma requête : grep -r "lists.ubuntu.com" /home/edd/Documents/FCM25/Weekly\ news/ En résumé, recherchez mon motif dans un répertoire (nombre de fois où j’ai cité lists.ubuntu.com comme source). On peut également utiliser -R ici. Notre résultat est donc légèrement différent. J’ai le chemin d’accès complet du fichier, suivi d’un :-> (qui n’est pas un smiley dans ce cas) et des occurrences où il a été trouvé. Remarque : je ne peux pas simplement faire ceci : grep "lists.ubuntu.com" /home/edd/Documents/FCM25/Weekly\ news/ - car la cible de ma recherche est un dossier, pas un fichier. **We can clean up our output with -h option/flag/tack, removing the path. See what I did there? I want you to do this on your own files, to get a feeling. Easiest is to use some text files, though it will work on config files, etcetera, but I’d rather you start with files you can modify freely. Though we usually just search for patterns, you *can explicitly search for words. This can be helpful when you have multiple parts that conform to your pattern, but you want something specific. I have a file that contains rgb and rgba. If I were to seach for the pattern rgb, it would return all the rgba instances as well. Here is my query: grep -w "rgb" /home/edd/dotfile.txt Broken down, I want only the “word” rgb to be returned out of my target file. Versus the normal output: Let’s circle back to my article query, what if I wanted to know how many times it finds my pattern in each file that it traverses?** Nous pouvons nettoyer notre sortie avec l'option -h, en supprimant le chemin. Vous voyez ce que j'ai fait ? Je vous invite à le faire sur vos propres fichiers, pour vous faire une idée. Le plus simple est d'utiliser des fichiers texte, même si cela fonctionne avec les fichiers de configuration, etc., mais je préfère commencer avec des fichiers que vous pouvez modifier librement. Bien que nous recherchions généralement uniquement des motifs, vous pouvez rechercher explicitement des mots. Cela peut être utile lorsque plusieurs parties correspondent à votre motif, mais que vous recherchez quelque chose de spécifique. J'ai un fichier contenant rgb et rgba. Si je recherchais le motif rgb, toutes les instances rgba seraient également renvoyées. Voici ma requête : grep -w "rgb" /home/edd/dotfile.txt En résumé, je souhaite que seul le « mot » rgb soit renvoyé de mon fichier cible. Par rapport à la sortie normale : Revenons au thème de cet article : que se passerait-il si je voulais savoir combien de fois mon motif est détecté dans chaque fichier parcouru ? **Here’s my query: grep -R -c "lists.ubuntu.com" /home/edd/Documents/FCM25/Weekly\ news/ Broken down, find my pattern, then tell me how many times it occurs inside each file. Note that we have a full path like before, but not the location of our pattern. How about if we have a few documents and we want to find out precisely where the pattern occurs? Here’s my query: grep -R -n "lists.ubuntu.com" /home/edd/Documents/FCM25/Weekly\ news/ Broken down, recursively search for my pattern and give me the line number where you found the match. Boom! ** Voici ma requête : grep -R -c "lists.ubuntu.com" /home/edd/Documents/FCM25/Weekly\news/ En détail, trouvez mon motif, puis indiquez-moi combien de fois il apparaît dans chaque fichier. Notez que nous avons un chemin complet comme précédemment, mais pas l'emplacement de notre motif. Et si nous avions plusieurs documents et que nous souhaitions savoir précisément où le motif apparaît ? Voici ma requête : grep -R -n "lists.ubuntu.com" /home/edd/Documents/FCM25/Weekly\news/ Soit, recherchez mon motif de manière récursive et indiquez-moi le numéro de ligne où vous avez trouvé la correspondance. Boum ! **I’m going to leave it here for this issue, as it is getting a bit image heavy, (I don’t want Ronnie to fire me, yet) but we can talk about it more in the next issue. For those of you that saw the youtube video about figuring out who wrote what in the constitution, yes, this is inspired by that. One gentleman used a certain phrase the others did not, so searching for it, sort of identified his contributions. Though we cannot say for sure, there is certainty that he wrote certain documents. Any corrections, we are all human, to: misc@fullcirclemagazine.org** Je vais m'arrêter là pour ce numéro, car il commence à être un peu chargé en images (je ne veux pas que Ronnie me vire pour l'instant), mais nous en reparlerons dans le prochain numéro. Pour ceux d'entre vous qui ont vu la vidéo YouTube expliquant comment déterminer qui a écrit quoi dans la constitution, oui, c'est inspiré de cela. Un homme a utilisé une expression que d'autres n'ont pas utilisée, donc en la cherchant, j'ai en quelque sorte identifié ses contributions. Bien que nous ne puissions pas l'affirmer avec certitude, il est certain qu'il a rédigé certains documents. Pour toute correction, car nous sommes tous humains, écrivez à : misc@fullcirclemagazine.org