{{tag>Brouillon Regex Python Shell}} # Notes sed grep regex ## grep Voir : * `man regex` * [[grep avec option p comme AIX - Récupérer un paragraphe complet]] Voir aussi : * pcregrep ## Regex Exclude ~~~ ^((?!motif).)*$ ~~~ Grepper sur plusieurs lignes (match grep with line break) ~~~bash grep -zP '\S{64}\n\S{64}' ~~~ ### Extended regular expressions Source : https://www.gnu.org/software/sed/manual/html_node/Extended-regexps.html The only difference between basic and extended regular expressions is in the behavior of a few characters: ''?'', ''+'', parentheses, and braces ''{}''. While basic regular expressions require these to be escaped if you want them to behave as special characters, when using extended regular expressions you must escape them if you want them // to match a literal character //. Examples: ~~~ abc? becomes ‘abc\?’ when using extended regular expressions. It matches the literal string ‘abc?’. c\+ becomes ‘c+’ when using extended regular expressions. It matches one or more ‘c’. a\{3,\} becomes ‘a{3,}’ when using extended regular expressions. It matches three or more ‘a’. \(abc\)\{2,3\} becomes ‘(abc){2,3}’ when using extended regular expressions. It matches either ‘abcabc’ or ‘abcabcabc’. \(abc*\)\1 becomes ‘(abc*)\1’ when using extended regular expressions. Backreferences must still be escaped when using extended regular expressions. ~~~ Trouver des tabulations dans un fichier (GNU grep) you can use the Perl-style regexp ~~~bash grep -P '\t' * ~~~ ### Pb #### Pb binary file matches ~~~bash # grep -i -e '2020-11-24' daemon.log Binary file daemon.log matches ~~~ Solution ~~~bash grep -a -i -e '2020-11-24' daemon.log ~~~ ## head / tail Supprimer les deux dernières lignes ~~~bash head -n -2 myfile.txt ~~~ Supprimer les 4 primières lignes ~~~bash tail -n +4 myfile.txt ~~~ ## Sed Voir : * https://www.ibm.com/developerworks/library/l-sed1/index.html Matched text ~~~bash sed -i -e 's/^LoadModule mod_unique_id.c/#&/' /etc/proftpd/modules.conf ~~~ Commenter tout un fichier ~~~bash sed -i -e 's/^[^#]/#&/' /etc/snmp/snmp.conf ~~~ Supprimer tous les espaces en début de ligne ~~~bash sed -e 's/^\s\+//g' ~~~ Première lettre en majuscule ~~~bash sed -e 's/^./\U&/' ~~~ Insérer une ligne au début d'un fichier ~~~bash sed -i '1i/dev/mapper/vg_os-root / xfs defaults,noatime 1 1' /etc/fstab ~~~ Ou pour insérer le caractère '{' en première ligne ~~~bash sed -e '1 i\{' ~~~ Strip HTML ~~~bash sed -e 's/<[^>]*>//g' ~~~ Colonnes ~~~bash df -PhT |column -t grep -v -e '^#' /etc/fstab |column -t ~~~ Adresse IP ~~~bash rgrep -E --color -e '([0-9]{1,3}\.){3}[0-9]{1,3}' /var/www/plop/www.acme.fr/htdocs/ ~~~ Supprimer une ligne ~~~bash sed -i -e '/\/data/d' /etc/fstab ~~~ Supprimer toutes les lignes à partir du motif ~~~bash sed -e '/MODIF/,/$$/d' plop.txt ~~~ **$$** : jusqu'à la fin du fichier Supprimer les fins de ligne Source et explications : https://stackoverflow.com/questions/1251999/how-can-i-replace-a-newline-n-using-sed ~~~bash sed ':a;N;$!ba;s/\n/ /g' file ~~~ Afficher de la ligne n à la ligne m : ~~~bash cat -n launch.sh # ou grep -n -A7 my_function launch.sh # Puis (de la ligne 46 à la ligne 68) cat launch.sh | sed -n -e '46,68p' >> build.sh ~~~ ### Character Classes how to represent "alphanumeric or _ or -" That will be this character class: ''[[:alnum:]_-]'' Which means allow one of these: - Alpha numeric - Underscore - Hyphen It is important to keep hyphen at 1st or last position in character class to avoid escaping. ## Awk Voir : * https://www.redhat.com/sysadmin/gawk-word-game Utiliser les variables d'environement dans awk : ~~~bash awk -v a="$var1" -v b="$var2" 'BEGIN {print a,b}' ~~~ Dernier champ ; avant dernier champ ~~~bash awk '{print $NF}' awk '{print $(NF - 1)}' ~~~ Mettre en majuscule/minuscule et grepper ~~~bash awk '/sAMAccountName/ {print tolower($2)}' ~~~ Exemple ligne commençant par ''opencv'' ou ''libopencv'' ~~~bash apt-cache search opencv |awk '/^(lib)*opencv/ {print $1}' ~~~ Trouver les zombies ~~~bash ps aux | awk '$8 ~ /^[Zz]/' ~~~ Remplacer un motif par un autre ~~~ $ echo "Bobby is cool" | awk '{sub("Bobby","Teddy"); print}' Teddy is cool ~~~ Exemple ~~~bash ip link |awk '/: br-/ { gsub(":", "") ; print $2 }' ~~~ Awk One-Liners - Remove duplicate, nonconsecutive lines ~~~bash iptables-save |awk ' !x[$0]++' |iptables-restore ~~~ sum - total - faire l'addition / la somme de nombres séparés par des sauts de ligne ~~~bash awk '{s+=$1} END {printf "%.0f", s}' fichiers.txt ~~~ if greater / less than ~~~bash awk -F':' '$3 >=1000 && $3 <=65534 {print $3}' /etc/passwd ~~~ Avant-dernier champs ~~~bash awk '{ print ( $(NF-1) ) }' ~~~ Remplacer un motif par un autre (remplace) ~~~bash awk '/^gpg: key / {gsub(":", "") ; print $3 ;}') ~~~ Lire une valeur dans un fichier ini en supprimant les espaces ''config.ini'' ~~~ini process_name = appsrvd ~~~ ~~~bash awk -F= '/process_name/ { gsub (" ", "", $0) ; print $2 }' config.ini ~~~ Calcul ~~~bash calc() { awk "BEGIN { print $* }"; } calc_sum() { awk '{s+=$1} END {printf "%.0f", s}' "$*" } ~~~ ### Awk autres ''/etc/auto.smb'' ~~~bash # ......... $SMBCLIENT -gNL $key 2>/dev/null| awk -v key="$key" -v opts="$opts" -F'|' -- ' BEGIN { ORS=""; first=1 } /Disk/ { if (first) print opts; first=0 dir = $2 loc = $2 # Enclose mount dir and location in quotes # Double quote "$" in location as it is special gsub(/\$$/, "\\$", loc); print " \\\n\t \"/" dir "\"", "\"://" key "/" loc "\"" } END { if (!first) print "\n"; else exit 1 } ' ~~~ ## Python **re.match** \\ La méthode match recherche une correspondance uniquement au début de la chaîne **re.search** \\ search() La fonction recherchera le modèle d’expression régulière et renverra la première occurrence. \\ Contrairement à Python re.match(), il vérifiera toutes les lignes de la chaîne d'entrée. La fonction Python re.search() renvoie un objet match lorsque le modèle est trouvé et « nul » si le modèle n'est pas trouvé **re.findall** \\ findall() Le module est utilisé pour rechercher « toutes » les occurrences qui correspondent à un modèle donné. En revanche, le module search() ne renverra que la première occurrence correspondant au modèle spécifié. \\ findall() parcourra toutes les lignes du fichier et renverra toutes les correspondances de modèle qui ne se chevauchent pas en une seule étape. ## Exemple de regex ~~~python email_re = re.compile(r'([a-zA-Z0-9_\+\-\.]+)@(([[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)') ~~~ ## Autres ### Tr SC1017 (error): Literal carriage return. Run script through ~~~bash tr -d '\r' . ~~~ Convertir les fins de ligne en null char ~~~bash tr '\n' '\0' ~~~ ### Preserve file timestamp in multifile string replace Source : https://gist.github.com/u0d7i/c03e34e57802d0b6347a#file-preserve_date_in_replace-txt ~~~bash # -I to grep ignores binary files, # @ in sed works as separator for strings with / # -r in touch uses existing file timestap as a reference grep -IR aaaa /somepath/ | awk -F: '{print $1}' | while read line; do touch -r $line /tmp/timeref; sed -i 's@aaaa@bbbb@' $line; touch -r /tmp/timeref $line; done ~~~