Bonjour,
8O ben, non : c'est un alias pour egrep. :ptdr:Citation:
Envoyé par yacinechaouche
EDIT: quand tu auras corrigé ton message, je supprimerai celui-ci. :ccool:
Version imprimable
Bonjour,
8O ben, non : c'est un alias pour egrep. :ptdr:Citation:
Envoyé par yacinechaouche
EDIT: quand tu auras corrigé ton message, je supprimerai celui-ci. :ccool:
Arf ! ^^' J'ai même pas lu en plus.
Je confond avec un autre alias qui anonymize les logs
Code:
1
2
3
4
5
6
7 15:29:35 ~ -1- $ type anonymize anonymize is a function anonymize () { sed 's/<[a-zA-Z0-9.\-]\+@\([^@]\+\)>/<xxx@\1>/g; s/mondomaine.tld/mydomain.tld/g; s/monautredomain.tld/mydomain.tld/g' $@ } 15:30:10 ~ -1- $
Qui s'utilise comme ceci :
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13 15:29:24 ~ -1- $ head DATA/MESSAGERIE/log/dovecot.log | anonymize Feb 26 06:25:14 imap(t.boudena@mydomain.tld): Info: Disconnected: Logged out in=197 out=1004 Feb 26 06:25:15 auth: Debug: master in: USER 2 root@messagerie.mydomain.tld service=quota-status Feb 26 06:25:15 auth-worker(26053): Debug: sql(root@messagerie.mydomain.tld): query: SELECT email as user, password FROM users WHERE email = LOWER('root@messagerie.mydomain.tld') Feb 26 06:25:15 auth-worker(26053): Info: sql(root@messagerie.mydomain.tld): unknown user Feb 26 06:25:15 auth: Debug: userdb out: NOTFOUND 2 Feb 26 06:25:16 auth: Debug: auth client connected (pid=28155) Feb 26 06:25:16 auth: Debug: client in: AUTH 1 PLAIN service=imap secured session=1tQxvBZmkQAKCgoT lip=10.10.10.19 rip=10.10.10.19 lport=143 rport=35217 resp=<hidden> Feb 26 06:25:16 auth-worker(26053): Debug: sql(pub.guelma@mydomain.tld,10.10.10.19): query: SELECT email as user, password FROM users WHERE email = LOWER('pub.guelma@mydomain.tld') Feb 26 06:25:16 auth: Debug: client passdb out: OK 1 user=pub.guelma@mydomain.tld Feb 26 06:25:16 auth: Debug: master in: REQUEST 2065039361 28155 1 89b802566ac5a403b53ba5bdde6d2b47 session_pid=28157 request_auth_token 15:29:35 ~ -1- $
qui n'est pas un alias mais une fonction... :ptdr: :ptdr:
ne le prend pas mal : "des fois quand ça veut pas, ça veut pas". :lol:
Si quelqu'un connaît un joli pont du côté d'Alger avec une belle vue svp.
:ptdr:
Nom du script : system.window.trace
Compatible avec: Bash
Descriptif: visualiser les appels systèmes d'un programme en cours d'execution en cliquant sur sa fenêtre.
Dépendances : x11-utils (fournit la commande xprop)
Qui s'utilise comme ceci :Code:
1
2
3
4
5
6
7
8
9
10
11
12 15:30:10 ~ -1- $ type sys.window.trace sys.window.trace is aliased to `_asroot strace -fp $(sys.window.pid)' 15:54:09 ~ -1- $ type sys.window.pid sys.window.pid is aliased to `pid=$(xprop | grep PID); echo ${pid##*=}; unset pid' 15:54:14 ~ -1- $ type _asroot _asroot is a function _asroot () { (($EUID == 0)) && "$@" || sudo "$@" } 15:54:46 ~ -1- $
Peut être utile au débogage d'une application pour voir où ça bloque.Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 15:55:27 ~ -1- $ sys.window.trace [click sur une fenêtre] [sudo] password for ychaouche: Process 5930 attached with 3 threads [pid 5932] select(5, [4], NULL, NULL, NULL <unfinished ...> [pid 5930] restart_syscall(<... resuming interrupted call ...> <unfinished ...> [pid 5931] restart_syscall(<... resuming interrupted call ...> <unfinished ...> [pid 5930] <... restart_syscall resumed> ) = 1 [pid 5930] recvmsg(6, {msg_name(0)=NULL, msg_iov(1)=[{"\10\4\200P\346\230Z\1\361\2\0\0\2\1\200\1\1\0`\4\215\4\214\2\205\4&\2\20\0\0\2"..., 4096}], msg_controllen=0, msg_flags=0}, 0) = 160 [pid 5930] recvmsg(6, 0x7ffc58540f00, 0) = -1 EAGAIN (Resource temporarily unavailable) [pid 5930] poll([{fd=6, events=POLLIN|POLLOUT}], 1, 4294967295) = 1 ([{fd=6, revents=POLLOUT}]) [pid 5930] writev(6, [{"(\3\4\0\361\2\0\0\2\1\200\1\225\1;\2", 16}, {NULL, 0}, {"", 0}], 3) = 16 [pid 5930] poll([{fd=6, events=POLLIN}], 1, 4294967295) = 1 ([{fd=6, revents=POLLIN}]) [pid 5930] recvmsg(6, {msg_name(0)=NULL, msg_iov(1)=[{"\6\0\200P\1\231Z\1\361\2\0\0\36\1\200\1\0\0\0\0\215\4\214\2\205\4\10\0\20\0\1\0"..., 4096}], msg_controllen=0, msg_flags=0}, 0) = 64 [pid 5930] recvmsg(6, 0x7ffc58540590, 0) = -1 EAGAIN (Resource temporarily unavailable) [pid 5930] recvmsg(6, 0x7ffc58540590, 0) = -1 EAGAIN (Resource temporarily unavailable)
je ne suis pas amateur de l'écriture des noms : ça fait un peu POO, ce que n'est pas du tout bash.
j'aurais nommé sysWindowTrace, sysWindowPID...
Et puis à lire la regex, il ne faut pas que le script soit un truc tordu du genre:
Après, on me dira qu'il faut vraiment chercher la petite bête...Code:
1
2 echo "foo rencontre bar \ ; donc foobar"
Pas sur, si on pense au fichier de type "csv" et le format "here-documents" du shell
Nom du script : net.ip.reputation
Compatible avec: Bash
Descriptif: connaître la réputation d'une adresse IP : envoi de spam, membre d'un botnet, IP résidentielle.
Dépendances : dnsutils qui procure la commande dig.
Elle s'utilise comme ceci :Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 function net.ip.reverse(){ local IFS; IFS=.; set -- $1; echo $4.$3.$2.$1; } function net.ip.reputation(){ local revip=$(net.ip.reverse "$1") local results=$(dig +short $revip.zen.spamhaus.org) for result in $results do case "$result" in 127.0.0.2) echo "SBL : SPAM sender" ;; 127.0.0.3) echo "CSS : snowshoe" ;; 127.0.0.[4-7]) echo "XBL/CBL: trojans, exploits" ;; 127.0.0.1[01]) echo "PBL(ISP) : not supposed to send mail" ;; *) echo "UNLISTED" ;; esac done }
Code:
1
2
3
4
5
6
7
8
9
10 root@messagerie-principale[10.10.10.19] ~ # net.ip.reputation 105.96.12.180 PBL(ISP) : not supposed to send mail root@messagerie-principale[10.10.10.19] ~ # net.ip.reputation 113.90.1.18 CSS : snowshoe PBL(ISP) : not supposed to send mail XBL/CBL: trojans, exploits root@messagerie-principale[10.10.10.19] ~ # net.ip.reputation 87.98.130.52 clean root@messagerie-principale[10.10.10.19] ~ #
function et () sont redondants : c'est l'un ou l'autre. Ça ne génère pas d'erreurs, mais c'est inutile.
Pour la suppression des commentaires en bash, on pourrait demander directement à celui-ci de le faire, par exemple:
fichier exemple:Code:
1
2
3
4 pretty.remove () { echo "$(eval 'f(){' "$(cat $1)" '; }' ; type f | sed '1,3d;$d;s/ //' )" }
execution:Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 $ cat bobo.bash # ~/.profile: executed by the command interpreter for login shells. # This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login # exists. # see /usr/share/doc/bash/examples/startup-files for examples. # the files are located in the bash-doc package. # the default umask is set in /etc/profile; for setting the umask # for ssh logins, install and configure the libpam-umask package. #umask 022 # set PATH so it includes user's private bin if it exists if [ -d "$HOME/.local/bin" ] ; then PATH="$HOME/.local/bin:$PATH" fi FOO=" TOTO #BIBI ;BAR "
Code:
1
2
3
4
5
6
7
8
9
10 $ pretty.remove bobo.bash if [ -d "$HOME/.local/bin" ]; then PATH="$HOME/.local/bin:$PATH"; fi; FOO=" TOTO #BIBI ;BAR "
Nom du script : pretty.box
Compatible avec: Bash
Descriptif: dessine de jolies en-têtes.
Dépendances : le paquet boxes qui fournit la commande eponyme.
Le script s'utilise comme ceciCode:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 16:50:38 ~ -1- $ type.cat pretty.box #!/bin/bash function _choose_model () { shuf -n1 -e xes whirly sunset stark2 stone stark1 spring simple shell scroll } while (($# != 0 )) do item=$1 # check if this is an option if [[ ${item:0:1} == - ]] then option=${item:1:2} if [[ $option == d ]] then model=$2 shift fi else string="$1" fi # end check if this was an option shift done ! [[ -v model ]] && model=$(_choose_model) echo chosen model is "$model" echo echo "$string" | boxes -d "$model" -ac 16:50:39 ~ -1- $
Pour donner un peu de gueule à vos fichiers de conf, code source etc. ExemplesCode:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 16:36:23 ~ -1- $ pretty.box "terminal configuration" chosen model is capgirl .-"```"-. /_______; \ (_________)\| / / a a \ \(_) / ( \___/ ) \ __ooo\__\_____/__/____ / \ | terminal configuration | \_________________ooo__/ / \ /:.:.:.:.:.:.:\ | | | \==|==/ /-'Y'-\ (__/ \__) 16:58:31 ~ -1- $ pretty.box "custom arguments for common commands" chosen model is whirly .+"+.+"+.+"+.+"+.+"+.+"+.+"+.+"+.+"+.+"+. ( ) ) custom arguments for common commands ( ( ) "+.+"+.+"+.+"+.+"+.+"+.+"+.+"+.+"+.+"+.+" 16:58:47 ~ -1- $
https://i.imgur.com/x4OAB7K.png
https://i.imgur.com/7zcnjjD.png
Nom du script : net.ip.info
Compatible avec: Bash
Descriptif: récupère la localisation de l'IP ainsi que le réseau auquel elle appartient
Dépendances : lft, qui fournit la commande whob
Elle s'utilise comme ceci :Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 17:13:41 ~ -1- $ type.cat net.ip.info #!/bin/bash # this needs to be called from awk scripts # this is why it is in its own file and not implemented as a bash function. IP=$1; if [[ ( $IP =~ ^10\. ) || ( $IP =~ ^192.168\. ) || ( $IP =~ ^172.16\. ) ]]; then echo "LAN"; exit 0; fi; echo "$IP" | whob | awk '/^Org-Name:/ {$1="";org=$0} /^Country-Code:/ {$1="";cc=$0} /^Region:/ {$1="";region=$0} END {printf("%s %-16s %s\n",cc,region,org)}' #awk '/(^Org-Name:|^Region:|Country-Code:)/ {$1=""; printf("%s",$0)} END {print ""}' 17:13:41 ~ -1- $
Peut être utile pour avoir une vue des connexions entrantes à votre machine, par exemple.Citation:
16:58:47 ~ -1- $ net.ip.info $(dig +short developpez.net)
FR Hauts-de-France OVH
17:12:20 ~ -1- $ net.ip.info $(dig +short google.org)
US California Google LLC
17:12:31 ~ -1- $ net.ip.info $(dig +short 1and1.com)
US Pennsylvania IONOS Inc.
17:12:39 ~ -1- $ net.ip.info $(dig +short ikea.com)
ES Madrid, Comunidad de Akamai International, BV
17:12:55 ~ -1- $
Nom du script : net.connexions.from.outside
Compatible avec: Bash
Descriptif: voir en live les connexions entrantes à votre serveur ainsi que l'origine des IP (lieu + nom du réseau)
Dépendances :
1. lft (fournit la commande [I]whob/I])
2. une variable INTERFACE définit dans votre .bashrc qui contient le nom de l'interface réseau qui reçoit les connexions depuis l'exterieur
3. le script net.ip.info fournit
4. le script tcpdump.ip.info fournit
voici le script bash net.conneions.from.outside
Elle requiere la variable INTERFACE qui devrait être dans votre .bashrcCode:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 function _asroot(){ (($EUID == 0)) && "$@" || sudo "$@"; } _tcpdump_default_args="-i $INTERFACE -q -l -n" _tcpdump_default_filter="host $(net.ip.private) and tcp[13]==2" function net.connexions(){ if (($# > 1)) then command_w_args="_asroot tcpdump $_tcpdump_default_args $@" else command_w_args="_asroot tcpdump $_tcpdump_default_args $_tcpdump_default_filter" fi echo $command_w_args $command_w_args } alias net.connexions.from.outside="net.connexions $_tcpdump_default_filter and src $_tcpdump_filter_outside | tcpdump.ip.info IP_column=3"
Code:
1
2 export INTERFACE="eth4"
et voici tcpdump.ip.info qu'il appelle
ainsi que net.ip.InfoCode:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 #!/usr/bin/gawk -f BEGIN { regex="([[:digit:]]{1,3}\\.){3}[[:digit:]]{1,3}"; } $2 == "IP" { IP_info=""; # this is given on the command line IP_field=$IP_column match(IP_field,regex,A); "net.ip.info " A[0] | getline IP_info; printf("%s %-21s - %-21s %s\n",$1,$3,$5,IP_info); close("net.ip.info " A[0]); }
Code:
1
2
3
4
5
6
7
8
9
10
11
12 #!/bin/bash # this needs to be called from awk scripts # this is why it is in its own file and not implemented as a bash function. IP=$1; if [[ ( $IP =~ ^10\. ) || ( $IP =~ ^192.168\. ) || ( $IP =~ ^172.16\. ) ]]; then echo "LAN"; exit 0; fi; echo "$IP" | whob | awk '/^Org-Name:/ {$1="";org=$0} /^Country-Code:/ {$1="";cc=$0} /^Region:/ {$1="";region=$0} END {printf("%s %-16s %s\n",cc,region,org)}'
whob doit être téléchargé depuis https://pwhois.org/lft/index.who
Voici un exemple de sortie de la commande.
quitte à faire modulable :?Code:
1
2
3 $ isRoot() { (($UID)) && { >&2 echo "Désolé, $USER n'est pas root."; return 1;};} $ isSudoer() { sudo -v;} $ asRootORsudo() { if isRoot; then "@"; elif isSudoer; then sudo "$@"; else return 1; fi;}
Nom du script : type.cat, type.edit, type.file
Compatible avec: Bash
Descriptif:
1. type.cat Affiche le code d'un script bash sans en donner le chemin complet
2. type.edit Edit le code d'un script bash sans en donner le chemin complet
3. type.file Execute la commande file sur une commande sans en donner le chemin complet
Dépendances :
1. string.word.last fournie
2. La variable EDITOR contenant votre editeur favori, c'est à dire emacs.
Celle-ci devrait être définie dans votre .bashrc
Voici le code de string.word.last ainsi que d'autres fonctions de la même famille.Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 function _type.command { # _type.command edit mail.user.new # opens mail.user.new for editing # _type.command cat mail.user.new local command="$1" local _type=$(type -t "$2") if [[ "$_type" == "file" ]] then local _path=$(string.word.last "$(type $2)") [[ $_path =~ (*) ]] && _path=$_path{1: -1} $command "$_path" else type "$1" fi } alias type.cat="_type.command cat" alias type.edit="_type.command ${EDITOR:-emacs}" alias type.file="_type.command file"
Et voici comment appeler les scripts type.cat et type.editCode:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 #-*- shell-script -*- function string.word.first { echo ${1%% *} } function string.word.first.remove { echo ${1#* } } function string.word.last { echo ${1##* } } function string.word.last.remove { echo ${1% *} }
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 root@messagerie-principale[10.10.10.19] ~ # type mail.user.new mail.user.new is /usr/local/scripts/mail/mail.user.new root@messagerie-principale[10.10.10.19] ~ # type.cat mail.user.new | head -30 #!/bin/bash # .--, .--, # ( ( \.---./ ) ) # '.__/o o\__.' # {= ^ =} # > - < # __.""`-------`"".__ # / \ # \ Exit statuses / # / \ # \___________________/ # ___)( )(___ # (((__) (__))) ######################################### # 1 -> insufficient number of arguments # # 2 -> mailbox exists # # 3 -> user cancellation # # 4 -> mailbox renamed # # 5 -> password too weak # ######################################### source mailutils if [[ "$#" < 2 ]] then echo "usage : $0 boite@domain.com name [password]" exit 1 root@messagerie-principale[10.10.10.19] ~ # type.edit mail.user.new [ouvre le fichier source de la commande mail.user.new dans l'éditeur définie par la variable $EDITOR] root@messagerie-principale[10.10.10.19] ~ #
Voici un exemple d'utilisation de type.file
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 13:30:54 ~ -1- $ type uzbl uzbl is /usr/bin/uzbl 13:31:42 ~ -1- $ type.file uzbl /usr/bin/uzbl: symbolic link to `uzbl-browser' 13:31:45 ~ -1- $ type.file uzbl-browser /usr/bin/uzbl-browser: POSIX shell script, ASCII text executable 13:34:31 ~ -1- $ type.cat uzbl-browser | head -30 #!/bin/sh # # This script implements a more useful out-of-the-box "browsing experience". # It does so by combining uzbl-core with a set of "recommended" tools and # practices. See docs for more info. # # If you want to customize the behavior any of the helper tools, copy them # to your $XDG_DATA_HOME/uzbl/scripts/ and edit them PREFIX=/usr export PREFIX EXAMPLES=$PREFIX/share/uzbl/examples XDG_DATA_HOME=${XDG_DATA_HOME:-$HOME/.local/share} export XDG_DATA_HOME XDG_CACHE_HOME=${XDG_CACHE_HOME:-$HOME/.cache} export XDG_CACHE_HOME XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config} export XDG_CONFIG_HOME # assure the relevant directories exist. for dir in "$XDG_CACHE_HOME"/uzbl "$XDG_DATA_HOME"/uzbl "$XDG_CONFIG_HOME"/uzbl do if [ ! -d "$dir" ] then if ! mkdir -p "$dir" then 13:34:33 ~ -1- $
a priori, non. D'ailleurs, que ferais bash d'un gestionnaire de paquet ?
Précise ta pensée, s'il te plaît.
J'ai trouvé ça mais ça n'a rien d'extra-ordinaire. Je me demandais si on pouvais faire bcp mieux.
je ne vois pas l'intérêt d'un tel programme. Ça paraît bien lourd pour quelques opérations triviales.
Petit correctif à la ligne 10 de _type.command
Au lieu de
Il fallaitCode:[[ $_path =~ (*) ]] && _path=$_path{1: -1}
Code:[[ "$_path" =~ \(*\) ]] && _path=${_path: 1: -1}
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 $ type _type.command _type.command is a function _type.command () { local command="$1"; local _type=$(type -t "$2"); if [[ "$_type" == "file" ]]; then local _path=$(string.word.last "$(type $2)"); [[ "$_path" =~ \(.*\) ]] && _path=${_path:1: -1}; $command "$_path"; else type "$1"; fi } $
une simplification :pas testé, parce qu'il n'est pas dit quels arguments attend la fonction.Code:
1
2
3
4
5
6
7
8
9 _typeCommand () { if test "$(type -t "$2")" = "file" then $1 $(path=$(stringWordLast "$(type $2)"); echo "${path//[()]}") else type "$1" fi }
Merci ! ça marche à merveille !Code:$1 $(path=$(stringWordLast "$(type $2)"); echo "${path//[()]}")
Ça prend bien en compte les deux cas; chemin avec et sans parenthèses.Code:
1
2
3
4
5
6
7
8
9
10 10:18:43 ~ -1- $ type man man is /usr/bin/man 10:19:13 ~ -1- $ type.file man /usr/bin/man: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=f421457c024fcd196f0ac9ccfc8796f59bddb3c4, stripped 10:19:15 ~ -1- $ type file file is hashed (/usr/local/bin/file) 10:19:17 ~ -1- $ type.file file /usr/local/bin/file: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=92eeb60f60d4cb4cc7cc8401bbc6db71cfe89820, stripped 10:19:18 ~ -1- $
Il faut que je regarde ça de plus près.
Ok, j'avais pourtant pris note mais je n'ai pas pensé à l'utiliser
Citation:
*** replace substring (no more sed for this !)
use ${var/pat/pat} to replace just one occurence
use ${var//pat/pat} to replace all occurences
example :Code:
1
2
3
4
5
6 $ url="https://distrowatch.com/dwres-mobile.php?resource=ratings&distro=sparky" $ echo ${url} https://distrowatch.com/dwres-mobile.php?resource=ratings&distro=sparky $ echo ${url/distrowatch.com/google.com} https://google.com/dwres-mobile.php?resource=ratings&distro=sparky $
Nom du script : package.describe, package.whatprovides
Compatible avec: Bash
Descriptif:
1. package.describe : affiche le descriptif d'un paquet sur un système reposant sur le framework APT (Debian et dérivés)
2. package.whatprovides : affiche le paquet qui procure une commande (ou un fichier) sur un système Debian ou dérivé.
Dépendances :
1. apt
2. grep-dctrl, fournit par le paquet dctrl-tools
Voici un exemple d'éxecution des deux commandesCode:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 $ type package.describe package.describe is a function package.describe () { apt-cache show "$1" | grep-dctrl -s Description-en - } $ $ type package.whatprovides package.whatprovides is a function package.whatprovides () { dpkg -S "$1" | cut -f1 -d: | sort | uniq } $
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 $ package.describe sshpass Description-en: Non-interactive ssh password authentication SSH's (secure shell) most common authentication mode is called "interactive keyboard password authentication", so called both because it is typically done via keyboard, and because openssh takes active measures to make sure that the password is, indeed, typed interactively by the keyboard. Sometimes, however, it is necessary to fool ssh into accepting an interactive password non-interactively. This is where sshpass comes in. . SECURITY NOTE: There is a reason openssh insists that passwords be typed interactively. Passwords are harder to store securely and to pass around securely between programs. If you have not looked into solving your needs using SSH's "public key authentication", perhaps in conjunction with the ssh agent (RTFM ssh-add), please do so before being tempted into using this package. $ package.whatprovides bin/grep-dctrl dctrl-tools $
Bonjour :coucou:
On pourra remplacer avantageusement | sort | uniq par | sort -u. Le cas où l'enchaînement des 2 commandes est obligatoire, c'est quand on compte les éléments. Sinon, sort seul suffit.Citation:
Code:dpkg -S "$1" | cut -f1 -d: | sort | uniq
Et si l'ordre n'a pas d'importance, on peut même faire un seul awk pour remplacer tous les derniers étages de la conduite.
gawk peut trier. Mais cela peut s'avérer plus galère qu'un simple sort.Code:dpkg -S "$1" | awk -F: '{a[$1]++;} END{for (i in a) print i;}'
Salut Flodelarab !
Merci pour le code AWK c'est tip-top !
par contre pour sort -u j'ai ça
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 13:36:07 /usr/share/doc/ubuntu-keyring -1- $ sort -u /tmp/out dctrl-tools: /usr/bin/grep-aptavail dctrl-tools: /usr/bin/grep-available dctrl-tools: /usr/bin/grep-dctrl dctrl-tools: /usr/bin/grep-debtags dctrl-tools: /usr/bin/grep-status emacs24-bin-common: /usr/bin/grep-changelog.emacs24 13:36:10 /usr/share/doc/ubuntu-keyring -1- $ sort /tmp/out dctrl-tools: /usr/bin/grep-aptavail dctrl-tools: /usr/bin/grep-available dctrl-tools: /usr/bin/grep-dctrl dctrl-tools: /usr/bin/grep-debtags dctrl-tools: /usr/bin/grep-status emacs24-bin-common: /usr/bin/grep-changelog.emacs24 13:36:28 /usr/share/doc/ubuntu-keyring -1- $
arf, désolé...
La solution avec AWK est nettement plus rapide
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 $ command ls -1 /usr/lib/ > /tmp/allthelibs $ for i in {1..1000}; do echo $i; shuf /tmp/allthelibs >> /tmp/allthelibs.shuffled.1000x; wc -l /tmp/allthelibs.shuffled.1000x; done [...] $ wc -l /tmp/allthelibs.shuffled.1000x 1406405 /tmp/allthelibs.shuffled.1000x $ time (awk '{A[$1]=""} END {for (i in A){print i}}' /tmp/allthelibs.shuffled.1000x > /dev/null) real 0m0.288s user 0m0.284s sys 0m0.000s $ time (sort /tmp/allthelibs.shuffled.1000x | uniq > /dev/null) real 0m2.176s user 0m5.728s sys 0m0.656s $ time (sort -u /tmp/allthelibs.shuffled.1000x > /dev/null) real 0m2.258s user 0m5.672s sys 0m0.696s $
pourquoi command ?
PS: quand la sortie standard de ls n'est pas reliée à un terminal, l'affichage se fait par défaut sur une seule colonne.
Pour éviter l'alias ls
comment t'as fait pour formatter ls et command sur le forum ?Citation:
$ type ls
ls is aliased to `ls -lh'
$
pour éviter l'alias, ajoute un anti-slash devant la commande : \ls.
pour mettre une commande en ligne, utilise la balise [c] (et [\c] pour fermer).
@Flodelarab, même en triant (PROCINFO["sorted_in"]), awk est plus rapide.
Super astuce le \ ! merci N_BaH
Ok apparemment "ls" et 'ls' aussi.
Je dois révisier pourquoi j'ai utilisé command.
Je crois qu'à un moment donné j'ai du utiliser command grep dans un de mes scripts parce que grep était un alias de grep --color=always,
ce qui s'est avéré être une mauvaise idée.
Du coup lorsque mes scripts utilisaient grep et redirigaient la sortie vers un fichier,
celui-ci contenait plein de code couleurs.
J'ai du donc recourir à command grep.
Il faudrait que je puisse reproduire ça 1 2 c 4 pour voir.
Mais pour l'instant,
c'est bon week-end pour moi !
Quand on voit le résultat de sort -u et sort | uniq, on comprend que sort tri dabord et dédoublonne ensuite.
Tandis que pour awk, on lui dit de dédoublonne pour trier ensuite...
C'est donc pas étonnant qu'il soit plus rapide
PROCINFO est une extension GNU; un GNUism. :)