-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathzsh-lovers.1.txt
1535 lines (1309 loc) · 50.8 KB
/
zsh-lovers.1.txt
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
ZSH-LOVERS(1)
=============
NAME
----
zsh-lovers - tips, tricks and examples for the Z shell
SYNOPSIS
--------
Just read it. ;-)
OVERVIEW
--------
Whenever we look at the zsh manual we wonder why there are no examples or those
simply things in (shell) life. The zsh contains many features, but there was no
manpage with some examples (like procmailex(5)). That's why we wrote this
manpage.
Most of the tricks and oneliner come from the mailinglists zsh-users,
zsh-workers, google, newsgroups and from ourself. See section *LINKS* for
details.
Note: This manpage (zsh-lovers(1)) is *not* an official part of the Z shell! It's
just a just for fun - manpage ;) +
For comments, bugreports and feedback take a quick look at the section *BUGS*.
SHELL-SCRIPTING
---------------
This section provides some examples for often needed shellscript-stuff. Notice
that you should not use otherwise most examples won't work. +
Parse options in shellscripts. Example taken from ZWS by Adam Chodorowski
(http://www.chodorowski.com/projects/zws/[]):
----------------------------------------------
parse_options()
{
o_port=(-p 9999)
o_root=(-r WWW)
o_log=(-d ZWS.log)
zparseopts -K -- p:=o_port r:=o_root l:=o_log h=o_help
if [[ $? != 0 || "$o_help" != "" ]]; then
echo Usage: $(basename "$0") "[-p PORT] [-r DIRECTORY]"
exit 1
fi
port=$o_port[2]
root=$o_root[2]
log=$o_log[2]
if [[ $root[1] != '/' ]]; then root="$PWD/$root"; fi
}
# now use the function:
parse_options $*
----------------------------------------------
EXAMPLES
--------
Available subsections are *Aliases*, *Completion*, *Unsorted/Misc examples*,
*(Recursive) Globbing - Examples*, *Modifiers usage*, *Redirection-Examples*,
*ZMV-Examples* and *Module-Examples*.
ALIASES
~~~~~~~
Suffix aliases are supported in zsh since version 4.2.0. Some examples:
-----------------
alias -s tex=vim
alias -s html=w3m
alias -s org=w3m
-----------------
Now pressing return-key after entering 'foobar.tex' starts vim with
foobar.tex. Calling a html-file runs browser w3m. 'www.zsh.org' and pressing
enter starts w3m with argument www.zsh.org. +
Global aliases can be used anywhere in the command line. Example:
----------------------
$ alias -g C='| wc -l'
$ grep alias ~/.zsh/* C
443
----------------------
Some more or less useful global aliases (choose whether they are useful or not
for you on your own):
--------------------------------------------------------
alias -g ...='../..'
alias -g ....='../../..'
alias -g .....='../../../..'
alias -g CA="2>&1 | cat -A"
alias -g C='| wc -l'
alias -g D="DISPLAY=:0.0"
alias -g DN=/dev/null
alias -g ED="export DISPLAY=:0.0"
alias -g EG='|& egrep'
alias -g EH='|& head'
alias -g EL='|& less'
alias -g ELS='|& less -S'
alias -g ETL='|& tail -20'
alias -g ET='|& tail'
alias -g F=' | fmt -'
alias -g G='| egrep'
alias -g H='| head'
alias -g HL='|& head -20'
alias -g Sk="*~(*.bz2|*.gz|*.tgz|*.zip|*.z)"
alias -g LL="2>&1 | less"
alias -g L="| less"
alias -g LS='| less -S'
alias -g MM='| most'
alias -g M='| more'
alias -g NE="2> /dev/null"
alias -g NS='| sort -n'
alias -g NUL="> /dev/null 2>&1"
alias -g PIPE='|'
alias -g R=' > /c/aaa/tee.txt '
alias -g RNS='| sort -nr'
alias -g S='| sort'
alias -g TL='| tail -20'
alias -g T='| tail'
alias -g US='| sort -u'
alias -g VM=/var/log/messages
alias -g X0G='| xargs -0 egrep'
alias -g X0='| xargs -0'
alias -g XG='| xargs egrep'
alias -g X='| xargs'
--------------------------------------------------------
COMPLETION
~~~~~~~~~~
See also man 1 zshcompctl zshcompsys zshcompwid. zshcompctl is the old
style of zsh programmable completion, zshcompsys is the new completion
system, zshcompwid are the zsh completion widgets.
Some functions, like _apt and _dpkg, are very slow. You can use a cache
in order to proxy the list of results (like the list of available
debian packages) Use a cache:
---------------------------------------------------------------------------------------------------
zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path ~/.zsh/cache
---------------------------------------------------------------------------------------------------
Prevent CVS files/directories from being completed:
---------------------------------------------------------------------------------------------------
zstyle ':completion:*:(all-|)files' ignored-patterns '(|*/)CVS'
zstyle ':completion:*:cd:*' ignored-patterns '(*/)#CVS'
---------------------------------------------------------------------------------------------------
Fuzzy matching of completions for when you mistype them:
---------------------------------------------------------------------------------------------------
zstyle ':completion:*' completer _complete _match _approximate
zstyle ':completion:*:match:*' original only
zstyle ':completion:*:approximate:*' max-errors 1 numeric
---------------------------------------------------------------------------------------------------
And if you want the number of errors allowed by _approximate to
increase with the length of what you have typed so far:
---------------------------------------------------------------------------------------------------
zstyle -e ':completion:*:approximate:*' \
max-errors 'reply=($((($#PREFIX+$#SUFFIX)/3))numeric)'
---------------------------------------------------------------------------------------------------
Ignore completion functions for commands you don't have:
---------------------------------------------------------------------------------------------------
zstyle ':completion:*:functions' ignored-patterns '_*'
---------------------------------------------------------------------------------------------------
With helper functions like:
---------------------------------------------------------------------------------------------------
xdvi() { command xdvi ${*:-*.dvi(om[1])} }
---------------------------------------------------------------------------------------------------
you can avoid having to complete at all in many cases, but if you do,
you might want to fall into menu selection immediately and to have the
words sorted by time:
---------------------------------------------------------------------------------------------------
zstyle ':completion:*:*:xdvi:*' menu yes select
zstyle ':completion:*:*:xdvi:*' file-sort time
---------------------------------------------------------------------------------------------------
Completing process IDs with menu selection:
---------------------------------------------------------------------------------------------------
zstyle ':completion:*:*:kill:*' menu yes select
zstyle ':completion:*:kill:*' force-list always
---------------------------------------------------------------------------------------------------
If you end up using a directory as argument, this will remove the
trailing slash (useful in ln)
---------------------------------------------------------------------------------------------------
zstyle ':completion:*' squeeze-slashes true
---------------------------------------------------------------------------------------------------
cd will never select the parent directory (e.g.: cd ../<TAB>):
---------------------------------------------------------------------------------------------------
zstyle ':completion:*:cd:*' ignore-parents parent pwd
---------------------------------------------------------------------------------------------------
Another method for 'quick change directories'. Add this to your ~/.zshrc, then just enter
``cd ..../dir''
---------------------------------------------------------------------------------------------------
rationalise-dot() {
if [[ $LBUFFER = *.. ]]; then
LBUFFER+=/..
else
LBUFFER+=.
fi
}
zle -N rationalise-dot
bindkey . rationalise-dot
---------------------------------------------------------------------------------------------------
UNSORTED/MISC examples
~~~~~~~~~~~~~~~~~~~~~~
Hint: A list of valid glob Qualifiers can be found in zshexpn(1).
See ``man 1 zshexpn | less -p'' Qualifiers for details.
-------------------------------------------------------------------------------
# Get the names of all files that *don't* match a pattern *anywhere* on the
# file (and without ``-L'' because its GNUish)
$ print -rl -- *(.^e{'grep -q pattern $REPLY'})
# or
$ : *(.e{'grep -q pattern $REPLY || print -r -- $REPLY'})
# random numbers
$ echo $[${RANDOM}%1000] # random between 0-999
$ echo $[${RANDOM}%11+10] # random between 10-20
$ echo ${(l:3::0:)${RANDOM}} # N digits long (3 digits)
# reverse a word
$ echo "${(j::)${(@Oa)${(s::):-hello}}}"
# Show newest directory
$ ls -ld *(/om[1])
# random array element
$ FILES=( .../files/* )
$ feh $FILES[$RANDOM%$#FILES+1]
# cat first line in all files in this dir
$ for file (*(ND-.)) IFS= read -re < $file
# test if a parameter is numeric
$ if [[ $1 == <-> ]] ; then
echo numeric
else
echo non-numeric
fi
# Show me all the .c files for which there doesn't exist a .o file.
$ print *.c(e_'[[ ! -e $REPLY:r.o ]]'_)
# All files in /var/ that are not owned by root
$ ls -ld /var/*(^u:root)
# All files for which the owner hat read and execute permissions
$ echo *(f:u+rx:)
# The same, but also others don't have execute permissions
$ echo *(f:u+rx,o-x:)
# brace expansion - example
$ X=(A B C)
$ Y=(+ -)
$ print -r -- $^X.$^Y
A.+ A.- B.+ B.- C.+ C.-
# Fetch the newest file containing the string 'fgractg*.log' in the
# filename and contains the string 'ORA-' in it
$ file=(fgractg*.log(Nm0om[1]))
$ (($#file)) && grep -l ORA- $file
# without Zsh
$ files=$( find . -name . -o -prune -name 'fgractg*>log' -mtime 0 -print )
> if [ -n "$files" ]; then
> IFS='
> '
> set -f
> file=$(ls -td $files | head -1)
> grep -l ORA- "$file"
> fi
# keep specified number of child processes running until entire task finished
$ zsh -c 'sleep 1 & sleep 3 & sleep 2& print -rl -- $jobtexts'
# Remove zero length and .bak files in a directory
$ rm -i *(.L0) *.bak(.)
# print out files that don't have extensions
$ printf '%s\n' ^?*.*
$ printf '%s\n' ^?*.[^.]*(D)
$ ls -d -- ^?*.*(D)
# Finding files which does not contain a specific string
$ print -rl file* | comm -2 -3 - <(grep -l string file*)'
$ for f (file*(N)) grep -q string $f || print -r $f'
# Show/Check whether a option is set or not. It works both with $options as
# with $builtins
$ echo $options[correct]
off
$ $options[zle]
on
# Count the number of directories on the stack
$ print $((${${(z)${(f)"$(dirs -v)"}[-1]}[1]} + 1)) # or
$ dirs -v | awk '{n=$1}END{print n+1}'
# Matching all files which do not have a dot in filename
$ ls *~*.*(.)
# Show only the ip-address from ``ifconfig device''
# ifconfig from net-tools (Linux)
$ print ${${$(LC_ALL=C /sbin/ifconfig eth0)[7]}:gs/addr://}
# ifconfig from 4.2BSD {Free,Net,Open}BSD
$ print ${$(/sbin/ifconfig tun0)[6]}
# Ping all the IP addresses in a couple of class C's or all hosts
# into /etc/hosts
$ for i in {1..254}; do ping -c 1 192.168.13.$i; done
or
$ I=1
$ while ( [[ $I -le 255 ]] ) ; do ping -1 2 150.150.150.$I; let I++; done
or
$ for i in $(sed 's/#.*//' > /etc/hosts | awk '{print $2}')
: do
: echo "Trying $i ... "
: ping -c 1 $i ;
: echo '============================='
: done
# load all available modules at startup
$ typeset -U m
$ m=()
$ for md ($module_path) m=($m $md/**/*(*e:'REPLY=${REPLY#$md/}'::r))
$ zmodload -i $m
# Rename all files within a directory such that their names get a numeral
# prefix in the default sort order.
$ i=1; for j in *; do mv $j $i.$j; ((i++)); done
$ i=1; for f in *; do mv $f $(echo $i | \
awk '{ printf("%03d", $0)}').$f; ((i++)); done
$ integer i=0; for f in *; do mv $f $[i+=1].$f; done
# Find (and print) all symbolic links without a target within the current
# dirtree.
$ $ file **/*(D@) | fgrep broken
$ for i in **/*(D@); [[ -f $i || -d $i ]] || echo $i
$ echo **/*(@-^./=%p)
$ print -l **/*(-@)
# List all plain files that do not have extensions listed in `fignore'
$ ls **/*~*(${~${(j/|/)fignore}})(.)
# see above, but now omit executables
$ ls **/*~*(${~${(j/|/)fignore}})(.^*)
# Print out files that don't have extensions (require *setopt extendedglob*
# and *setopt dotglob*)
$ printf '%s\n' ^?*.*
# List files in reverse order sorted by name
$ print -rl -- *(On)
or
$ print -rl -- *(^on)
# Synonymic to ``ps ax | awk '{print $1}'''
$ print -l /proc/*/cwd(:h:t:s/self//)
# Get the PID of a process (without ``ps'', ``sed'', ``pgrep'', ..
# (under Linux)
$ pid2 () {
> local i
> for i in /proc/<->/stat
> do
> [[ "$(< $i)" = *\((${(j:|:)~@})\)* ]] && echo $i:h:t
> done
> }
# for X in 'n' 'o' 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' 'x' 'y'; do ...
$ for (( i = 36#n; i <= 36#y; i++ )); do
> print ${$(([##36]i)):l}
> done
# or in combination with ``dc''
$ print {$((##n))..$((##y))}P\ 10P | dc
# or with ``eval''
$ eval print '${$(([##36]'{$((36#n))..$((36#y))}')):l}'
# foreach in one line of shell
$ for f (*) print -r -- $f
# copy a directory recursively without data/files
$ dirs=(**/*(/))
$ cd -- $dest_root
$ mkdir -p -- $dirs
# or without zsh
$ find . -type d -exec env d="$dest_root" \
sh -c ' exec mkdir -p -- "$d/$1"' '{}' '{}' \;
# If `foo=23'', then print with 10 digit with leading '0'.
$ foo=23
$ print ${(r:10::0:)foo}
# find the name of all the files in their home directory that have
# 20 or more characters in their file names
print -rl $HOME/${(l:20::?:)~:-}*
# Save arrays
$ print -r -- ${(qq)m} > $nameoffile # save it
$ eval "m=($(cat -- $nameoffile)" # or use
$ m=("${(@Q)${(z)"$(cat -- $nameoffile)"}}") # to restore it
# get a "ls -l" on all the files in the tree that are younger than a
# specified age (e.g "ls -l" all the files in the tree that where
# modified in the last 2 days)
$ ls -tld **/*(m-2)
# This will give you a listing 1 file perl line (not à la ls -R).
# Think of an easy way to have a "ls -R" style output with
# only files newer than 2 day old.
$ for d (. ./**/*(/)) {
> print -r -- $'\n'${d}:
> cd $d && {
> l=(*(Nm-2))
> (($#l)) && ls -ltd -- $l
> cd ~-
> }
> }
# If you also want directories to be included even if their mtime
# is more than 2 days old:
$ for d (. ./**/*(/)) {
> print -r -- $'\n'${d}:
> cd $d && {
> l=(*(N/,m-2))
> (($#l)) && ls -ltd -- $l
> cd ~-
> }
> }
# And if you want only the directories with mtime < 2 days to be listed:
$ for d (. ./**/*(N/m-2)) {
> print -r -- $'\n'${d}:
> cd $d && {
> l=(*(Nm-2))
> (($#l)) && ls -ltd -- $l
> cd ~-
> }
> }
# print 42 ``-''
$ echo ${(l:42::-:)}
# or use ``$COLUMS''
$ echo ${(l:$COLUMNS::-:)}
# and now with colors (require autoload colors ;colors)
$ echo "$bg[red]$fg[black]${(l:42::-:)}"
# Redirect STDERR to a command like xless without redirecting STDOUT as well.
$ foo 2>>(xless)
# but this executes the command asynchronously. To do it synchronously:
$ { { foo 1>&3 } 2>&1 | xless } 3>&1
# Rename all MP3-Files from name with spaces.mp3 to Name With Spaces.mp3
$ for i in *.mp3; do
> mv $i ${${(C)i}:s/Mp3/mp3/}
> done
# Match file names containing only digits and ending with .xml (require
# *setopt kshglob*)
$ ls -l [0-9]##.xml
$ ls -l <0->.xml
# Remove all "non txt" files
$ rm ./^*.txt
# Move 200 files from a directory into another
$ mv -- *([1,200]) /another/Dir
# Convert images (foo.gif => foo.png):
$ for i in **/*.gif; convert $i $i:r.png
# convert a collection of mp3 files to wave or cdr,
# e.g. file.wav -> file.mp3)
$ for i (./*.mp3){mpg321 --w - $i > ${i:r}.wav}
# Download with LaTeX2HTML created Files (for example the ZSH-Guide):
$ for f in https://zsh.sourceforge.io/Guide/zshguide{,{01..08}}.html; do
> lynx -source $f >${f:t}
> done
# Move all files in dir1 and dir2 that have line counts greater than 10 to
# another directory say "/more10"
$ mv dir[12]/**/*.cr(-.e{'((`wc -l < $REPLY` > 10))'}) /more10
# Make with dpkg a master-list of everyfile that it has installed
$ diff <(find / | sort) <(cat /var/lib/dpkg/info/*.list | sort)
# Replace this fucking Escape-Sequences:
$ autoload colors ; colors
$ print "$bg[cyan]$fg[blue]You are a idiot" >> /dev/pts/3
# Get ASCII value of a character
$ char=N ; print $((#char))
# Filename "Erweiterung"
# Note: The (N) says to use the nullglob option for this particular
# glob pattern.
$ for i in *.o(N); do
> rm $i
> done
# Rename files; i. e. FOO to foo and bar to BAR
$ for i in *(.); mv $i ${i:l} # `FOO' to `foo'
$ for i in *(.); mv $i ${i:u} # `bar to `BAR'
# Show all suid-files in $PATH
$ ls -latg ${(s.:.)PATH} | grep '^...s'
# or more complex ;)
$ print -l ${^path}/*(Ns,S)
# or show only executables with a user given pattern
$ print -l ${^path}/*vim*(*N)
# gzip files when containing a certain string
$ gzip ${(ps:\0:)"$(grep -lZ foobar ./*.txt(.))"}
# A small one-liner, that reads from stdin and prints to stdout the first
# unique line i. e. does not print lines that have been printed before
# (this is similar to the unique command, but unique can only handle
# adjacent lines).
$ IFS=$'\n\n'; print -rl -- ${(Oau)${(Oa)$(cat file;echo .)[1,-2]}}
# Lists every executable in PATH
$ print -l ${^path}/*(-*N)
# Match all .c files in all subdirectories, _except_ any SCCS subdirectories?
$ ls **/*.c~(*/)#SCCS/*
# List all `README' - files case-insensitive with max. one typo
$ ls **/*(#ia2)readme
# case insensitive checking for variables
$ if [[ $OSTYPE == (#i)LINUX*(#I) ]]; then
> echo "Penguin on board."
> else
> echo "Not a Linux."
> fi
-------------------------------------------------------------------------------
(Recursive) Globbing - Examples
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A list of valid glob Qualifiers can be found in zshexpn(1). *Note:*
\*\*/ is equivalent to (*/)#! For example:
-------------------------------------------------------------------------------
$ print (*/)#zsh_us.ps
zsh-4.2.3/Doc/zsh_us.ps
$ print **/zsh_us.ps
zsh-4.2.3/Doc/zsh_us.ps
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
# Search for `README' in all Subdirectories
$ ls -l **/README
# find directories that contain both "index.php" and "index.html", or in
# general, directories that contain more than one file matching "index.*"
$ ls **/*(D/e:'[[ -e $REPLY/index.php && -e $REPLY/index.html ]]':)
# or
$ ls **/*(D/e:'l=($REPLY/index.*(N)); (( $#l >= 2 ))':)
# Find command to search for directory name instead of basename
$ print -rl /**/*~^*/path(|/*)
# or - without Zsh
$ find / | grep -e /path/ -e '/path$'
# Print he path of the directories holding the ten biggest C regular files
# in the current directory and subdirectories.
$ print -rl -- **/*.c(D.OL[1,10]:h) | sort -u
# Find files with size == 0 and send a mail
$ files=(**/*(ND.L0m+0m-2))
> (( $#files > 0 )) && print -rl -- $files | \
mailx -s "empty files" [email protected]
# recursive chmod
$ chmod 700 **/(.) # Only files
$ chmod 700 **/(/) # Only directories
# print out all of the files in that directory in 2 columns
$ print -rC2 -- ${1:[...]}/*(D:t)
# ^- number ob columns
# or - if you feel concerned about special characters - use
$ list=(${1:[...]}/*(ND:t))
$ (($#list)) && print -rC2 -- ${(V)list}
# Search all files in /home/*/*-mail/ with a setting ``chmod -s'' flag
# (recursive, include dotfiles) remove the setgid/setuid flag and print
# a message
$ chmod -s /home/*/*-mail(DNs,S) /home/*/*-mail/**/*(DNs,S))
# or with a small script
$ for file (/home/*/*-mail(DNs,S) /home/*/*-mail/**/*(DNs,S)) {
> print -r -- $file
> chmod -s $file && print -r fixed $file
> }
# or use ``zargs'' (require autoload zargs) prevent the arg list too
# long error
$ zargs /home/*/*-mail(DNs,S) /home/*/*-mail/**/*(DNs,S)) -- chmod -s
# List files beginning at `foo23' upwards (foo23, foo24, foo25, ..)
$ ls -l foo<23->
# get all files that begin with the date strings from June 4 through
# June 9 of 2004
$ ls -l 200406{04..10}*(N)
# or if they are of the form 200406XX (require ``setopt extended_glob''
$ ls -l 200306<4-10>.*
# remove spaces from filenames
$ for a in ./**/*\ *(Dod); do mv $a ${a:h}/${a:t:gs/ /_}; done
# Show only all *.c and *.h - Files
$ ls -l *.(c|h)
# Show only all *.c - files and ignore `foo.c'
$ ls *.c~foo.c
# show data to *really* binary format
$ zsh -ec 'while {} {printf %.8x $n;repeat 8 \
> {read -ku0 a printf \ %.8d $(([##2]#a))};print;((n+=8))}' < binary
# Show only world-readable files
$ ls -l *(R)
# List files in the current directory are not writable by the owner
$ print -l ~/*(ND.^w)
# find and delete the files which are older than a given parameter
# (seconds/minutes/hours)
# deletes all regular file in /Dir that are older than 3 hours
$ rm -f /Dir/**/*(.mh+3)
# deletes all symlinks in /Dir that are older than 3 minutes
$ rm -f /Dir/**/*(@mm+3)
# deletes all non dirs in /Dir that are older than 30 seconds
$ rm -f /Dir/**/*(ms+30^/)
# deletes all folders, sub-folders and files older than one hour
$ rm ./**/*(.Dmh+1,.DL0)
# deletes all files more than 6 hours old
$ rm -f **/*(mh+6)
# removes all files but the ten newer ones (delete all but last 10
# files in a directory)
$ rm ./*(Om[1,-11])
Note: If you get a arg list too long, you use the builtin rm. For
example:
$ zmodload zsh/files ; rm -f **/*(mh+6)
or use the zargs function:
$ autoload zargs ; zargs **/*(mh+6) -- rm -f
# A User's Guide to the Z-Shell /5.9: Filename Generation and Pattern
# Matching find all files in all subdirectories, searching recursively,
# which have a given name, case insensitive, are at least 50 KB large,
# no more than a week old and owned by the root user, and allowing up
# to a single error in the spelling of the name. In fact, the required
# expression looks like this:
$ ls **/(#ia1)name(LK+50mw-1u0)
# Change the UID from 102 to 666
$ chown 666 **/*(u102)
# List all files which have not been updated since last 10 hours
$ print -rl -- *(Dmh+10^/)
# delete only the oldest file in a directory
$ rm ./*filename*(Om[1])
# Sort the output from `ls -l' by file size
$ ls -fld *(OL)
# find most recent file in a directory
$ setopt dotglob ; print directory/**/*(om[1])
# Show only empty files which nor `group' or `world writable'
$ ls *(L0f.go-w.)
# Find - and list - the ten newest files in directories and subdirs.
# (recursive)
$ print -rl -- **/*(Dom[1,10])
# Print only 5 lines by "ls" command (like ``ls -laS | head -n 5'').
$ ls -fl *(DOL[1,5])
# Display the 5-10 last modified files.
$ print -rl -- /path/to/dir/**/*(D.om[5,10])
# Find all files without a valid owner.
$ chmod someuser /**/*(D^u:${(j.:u:.)${(f)"$(</etc/passwd)"}%%:*}:)
# Find all the empty directories in a tree.
$ for f in ***/*(/l2); do foo=($f/*(N)); [[ -z $foo ]] && print $f; done
# Note:Since Zsh 4.2.1 the glob qualifier F indicates a non-empty directory.
# Hence *(F) indicates all subdirectories with entries, *(/^F) means all
# subdirectories with no entries.
$ ls -ld *(/^F)
# Remove empty directories afterwards.
$ rmdir ./**/*(/od) 2> /dev/null
# Show only files which are owned by group `users'.
$ ls -l *(G[users])
-------------------------------------------------------------------------------
Modifiers usage
~~~~~~~~~~~~~~~
Modifiers are a powerful mechanism that let you modify the results
returned by parameter, filename and history expansion. See zshexpn(1)
for details.
-------------------------------------------------------------------------------
# NOTE: Zsh 4.3.4 needed!
$ autoload -U age
# files modified today
$ print *(e:age today now:)
# files modified since 5 pm
$ print *(e-age 17:00 now-)
# ... since 5 o'clock yesterda
$ print *(e-age yesterday,17:00 now-)
# ... from last Christmas before today
$ print *(e-age 2006/12/25 today-)
# ... before yesterday
$ print *(e-age 1970/01/01 yesterday-)
# all files modified between the start of those dates
$ print *(e:age 2006/10/04 2006/10/09:)
# all files modified on that date
$ print *(e:age 2006/10/04:)
# Supply times.
$ print *(e-age 2006/10/04:10:15 2006/10/04:10:45-)
# Remove a trailing pathname component, leaving the head. This works like
# `dirname'.
$ echo =ls(:h)
/bin
# Remove all leading pathname components, leaving the tail. This works
# like `basename'.
$ echo =ls(:t)
ls
# Remove the suffix from each file (*.sh in this example)
$f:e is $f file extension
:h --> head (dirname)
:t --> tail (basename)
:r --> rest (extension removed)
$ for f (*.sh) mv $f $f:r
# Remove a filename extension of the form `.xxx', leaving the root name.
$ echo $PWD
/usr/src/linux
$ echo $PWD:t
linux
# Remove all but the extension.
$ foo=23.42
$ echo $foo
23.42
$ echo $foo:e
42
# Print the new command but do not execute it. Only works with history
# expansion.
$ echo =ls(:h)
/bin
$ !echo:p
$ echo =ls(:h)
# Quote the substituted words, escaping further substitutions.
$ bar="23'42"
$ echo $bar
23'42
$ echo $bar:q
23\'42
# Convert the words to all lowercase.
$ bar=FOOBAR
$ echo $bar
FOOBAR
$ echo $bar:l
foobar
# Convert the words to all uppercase.
$ bar=foobar
$ echo $bar
foobar
$ echo $bar:u
FOOBAR
# convert 1st char of a word to uppercase
$ foo="one two three four"
$ print -r -- "${(C)foo}"
One Two Three Four
-------------------------------------------------------------------------------
Redirection-Examples
~~~~~~~~~~~~~~~~~~~~
See zshmisc(1) for more information (or less ${^fpath}/zmv(N))
-------------------------------------------------------------------------------
# Append `exit 1' at the end of all *.sh - files
$ echo "exit 1" >> *.sh
# adding files to foobar.tar.gz
$ eval set =(gunzip < foobar.tar.gz) '
tar rf $1 additional.txt &&gzip < $1 > foobar.tar.gz'
# Redirect output to a file AND display on screen
$ foobar >&1 > file1 > file2 > ..
# pipe single output to multiple inputs
$ zcat foobar.Z >> (gzip -9 > file1.gz) \
>> (bzip2 -9 > file1.bz2) \
>> (acb --best > file1.acb)
# Append /etc/services at the end of file `foo' and `bar'
$ cat /etc/services >> foo >> bar
# Pipe STDERR
$ echo An error >&2 2>&1 | sed -e 's/A/I/'
# send standard output of one process to standard input of several processes
# in the pipeline
$ setopt multios
$ process1 > >(process1) > >(process2)
# initializing a variable and simultaneously keeping terminal output
$ setopt multios
$ { a=$(command >&1 >& 3 3 > &- 2>&1);} 3>&1
# redirect stderr two times
$ setopt multios ; program 2> file2 > file1 2>&1
# Duplicating stdout and stderr to a logfile
$ exec 3>&1 > logfile 2>&2 2>&1 >&3 3>&-
# redirect stderr (only) to a file and to orig. stderr:
$ command 2>&2 2>stderr
# redirect stderr and stdout to separate files and both to orig. stdout:
$ command 2>&1 1>&1 2>stderr 1>stdout
# redirect stderr and stdout to separate files and stdout to orig. stdout
# AND stderr to orig. stderr:
$ command 2>&2 1>&1 2>stderr 1>stdout
# More fun with STDERR ;)
$ ./my-script.sh 2> >(grep -v moron >error.log)|process-output >output.log
$ echo "Thats STDOUT" >>(sed 's/stdout/another example/' > foobar)
-------------------------------------------------------------------------------
ZMV-Examples (require autoload zmv)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*Note:* '-n' means no execution (just print what would happen). At
-------------------------------------------------------------------------------
# Remove illegal characters in a fat32 file system. Illegal characters are
# / : ; * ? " < > |
# NOTE: ``-Q'' and (D) is to include hidden files.
$ unwanted='[:;*?\"<>|]'
$ zmv -Q "(**/)(*$~unwanted*)(D)" '$1${2//$~unwanted/}'
# Changing part of a filename (i. e. "file-hell.name" -> "file-heaven.name")
$ zmv '(*)hell(*)' '${1}heaven${2}'
# or
$ zmv '*' '$f:s/hell/heaven/'
# remove round bracket within filenames
# i. e. foo-(bar).avi -> foo-bar.avi
$ zmv '*' '${f//[()]/}'
# serially all files (foo.foo > 1.foo, fnord.foo > 2.foo, ..)
$ autoload zmv
$ ls *
1.c asd.foo bla.foo fnord.foo foo.fnord foo.foo
$ c=1 zmv '*.foo' '$((c++)).foo'
$ ls *
1.c 1.foo 2.foo 3.foo 4.foo foo.fnord
# Rename "file.with.many.dots.txt" by substituting dots (except for the last
# one!) with a space
$ touch {1..20}-file.with.many.dots.txt
$ zmv '(*.*)(.*)' '${1//./ }$2'
# Remove the first 4 chars from a filename
$ zmv -n '*' '$f[5,-1]' # NOTE: The "5" is NOT a mistake in writing!
# Rename names of all files under the current Dir to lower case, but keep
# dirnames as-is.
$ zmv -Qv '(**/)(*)(.D)' '$1${(L)2}'
# replace all 4th character, which is "1", with "2" and so on
$ autoload -U zmv
$ zmv '(???)1(???[1-4].txt)' '${1}2${2}'
# Remove the first 15 characters from a string
$ touch 111111111111111{a-z}
$ autoload zmv
$ zmv '*' '$f[16,-1]'
# Replace spaces (any number of them) with a single dash in file names
$ autload zmv
$ zmv -n '(**/)(* *)' '$1${2//( #-## #| ##)/-}'
# or - with Bash
$ find . -depth -name '* *' -exec bash -c '
> shopt -s extglob
> file=$1
> dir=${file%/*}
> name=${file##*/}
> newname=${name//*([ -]) *([ -])/-}
> mv -i -- "$file" "$Dir/$newname"' {} {} \;
# Clean up file names and remove special characters
$ autoload zmv
$ zmv -n '(**/)(*)' '$1${2//[^A-Za-z0-9._]/_}'
# Add *.py to a bunch of python scripts in a directory (some of them end
# in *.py and give them all a proper extension
$ autoload zmv
$ zmv -n '(**/)(con*)(#qe,file $REPLY | grep "python script",)' '$1$2.py'
# lowercase all extensions (i. e. *.JPG) incl. subfolders
$ autoload zmv
$ zmv '(**/)(*).(#i)jpg' '$1$2.jpg'
# Or - without Zsh
$ find Dir -name '*.[jJ][pP][gG]' -print | while read f
> do
> case $f in
> *.jpg) ;
> *) mv "$f" "${f%.*}.jpg" ;
> esac
> done
# remove leading zeros from file extension
$ autoload zmv
$ ls
filename.001 filename.003 filename.005 filename.007 filename.009
filename.002 filename.004 filename.006 filename.008 filename.010
$ zmv '(filename.)0##(?*)' '$1$2'
$ ls
filename.1 filename.10 filename.2 filename.3 filename.4 filename.5 ..
# renumber files.
$ autoload zmv
$ ls *
foo_10.jpg foo_2.jpg foo_3.jpg foo_4.jpg foo_5.jpg foo_6.jpg ..
$ zmv -fQ 'foo_(<0->).jpg(.nOn)' 'foo_$(($1 + 1)).jpg'
$ ls *
foo_10.jpg foo_11.jpg foo_3.jpg foo_4.jpg foo_5.jpg ...
# adding leading zeros to a filename (1.jpg -> 001.jpg, ..
$ autoload zmv
$ zmv '(<1->).jpg' '${(l:3::0:)1}.jpg'
# See above, but now only files with a filename >= 30 chars
$ autoload zmv
$ c=1 zmv "${(l:30-4::?:)}*.foo" '$((c++)).foo'
# Replace spaces in filenames with a underline
$ autoload zmv
$ zmv '* *' '$f:gs/ /_'
# Change the suffix from *.sh to *.pl
$ autoload zmv
$ zmv -W '*.sh' '*.pl'
# Add a "".txt" extension to all the files within ${HOME}
# ``-.'' is to only rename regular files or symlinks to regular files,
# ``D'' is to also rename hidden files (dotfiles))
$ autoload zmv
$ zmv -Q '/home/**/*(D-.)' '$f.txt'
# Or to only rename files that don't have an extension:
$ zmv -Q '/home/**/^?*.*(D-.)' '$f.txt'
# Recursively change filenames with characters ? [ ] / = + < > ; : " , - *
$ autoload zmv
$ chars='[][?=+<>;",*-]'
$ zmv '(**/)(*)' '$1${2//$~chars/%}'
# Removing single quote from filenames (recursively)
$ autoload zmv
$ zmv -Q "(**/)(*'*)(D)" "\$1\${2//'/}"
# When a new file arrives (named file.txt) rename all files in order to
# get (e. g. file119.txt becomes file120.txt, file118.txt becomes
# file119.txt and so on ending with file.txt becoming file1.txt
$ autoload zmv
$ zmv -fQ 'file([0-9]##).txt(On)' 'file$(($1 + 1)).txt'
# lowercase/uppercase all files/directories
$ autoload zmv
$ zmv '(*)' '${(L)1}' # lowercase
$ zmv '(*)' '${(U)1}' # uppercase
# Remove the suffix *.c from all C-Files
$ autoload zmv
$ zmv '(*).c' '$1'
# Uppercase only the first letter of all *.mp3 - files
$ autoload zmv
$ zmv '([a-z])(*).mp3' '${(C)1}$2.mp3'
# Copy the target `README' in same directory as each `Makefile'
$ autoload zmv
$ zmv -C '(**/)Makefile' '${1}README'
# Removing single quote from filenames (recursively)
$ autoload zmv
$ zmv -Q "(**/)(*'*)(D)" "\$1\${2//'/}"