-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoneliners
8505 lines (6232 loc) · 407 KB
/
oneliners
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
###############################################################################
# Name: $HOME/code/misccode/oneliners
#
# Summary: Programming and sysadmin fragments I've collected over the last
# few decades. Section-searchable via ~/dotfiles/gone.sh. Comments
# are often written for searching, not proper English.
#
# °
# ~~~~~~~~°~~~~~~~~~~~
# ° °
# ° °°
# {°^°}=~~€ .. .
#
# ^^^^__^^^^^__^^^_^^^
#
# Created: 02-Jun-1998 (Bob Heckel)
# Modified: 29-Aug-2024 (Bob Heckel)
###############################################################################
xxVIMxx START:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-: {{{1
" Delete blank empty lines:
:g/^$/d
" Delete blank empty lines (including nonprinting characters):
:g/^\W\+$/d
" Thin out a file by deleting every other line:
:g/^/ + d
" or to delete 2/3 of the file:
:g/^/ +, ++ d
" Doublespace a file:
:%s/$/^M/g
" Insert a line, interleave, after each line in a file:
%s/$/^Mfoo bar/gc <--^M is control char Ctr+v + Return
" For each line containing UPRD37, do this substitution if rtpsduxrax exists:
:g/UPRD37/s/rtpsduxrax/us1sduxray/c
" Delete line 10 and the 3 lines following it (total 4 lines deleted)
:10d 4
" Delete all spaces from the lines between, but not including, After and Replicant:
:g/After/+,/Replicant/- s: \+::g
" Delete all *lines* containing the word emacs. E.g. 'Boot the emacs OS'
:g/\<emacs\>/d
" Delete all lines NOT containing any part of either of these words. global command uses the OR operator \| (chaining alternation multiple conditions):
:g/^foo\|^bar/d
" Yank all lines containing Emily into buffer a (must use uppercase register or only get last yank). Clear register A before beginning:
:let @a='' | :g/Emily/y A
" Delete line above a blank line (e.g. last line in a block or paragraph) into register a:
:let @a='' | :g/^$/-1 d A
" Highlight, view, trailing whitespace:
:se hls | /\s\+$/
" Strip all trailing whitespace (especially useful in MVS SAS files):
:%s:\s\+$::gc
" Surround each word with single quotes. E.g. foo, bar, baz, boom:
:%s/\(\w\+\)/'\1'/gc
" Find lines with 'Replicant', substitute. Then copy those lines to the bottom of the file:
:g/Replicant/s/were/WERE NOT/ | copy $
" Move all lines containing foo to EOF:
:g/foo/ co $
" Copy the line (or lines) preceding foo to the last line in the file:
:g/foo/- copy $
" Go up 2 lines to do the copy:
:g/foo/-- co $
" Moves a section of text below another section of text.
:g/StartOfBlockToMove/,/NextBlockStartHere/-1 mo /MoveToAboveThisLine/-1
" Append all (potentially non-contiguous) lines containing foo to junk.txt. Do NOT forget the '.' (current line address):
:g/foo/ . w >> t.txt
" or using marks:
:'a,'b g/foo/ . w >> t.txt
" Specify which lines, starting with Th, should have their e turned to E:
:,+15g/Th/s/e/E/gc
" Reverse all lines in a file (the zero is a noop where the matching lines, i.e. all of them, are continually placed):
:g/^/m0
" HTMLify (htmlize htmlify). TODO requires 2 passes. Misses first line:
:g/^$/+ s/^./<P>&/
:g/^$/- s:.$:&</P>:
" Show matches with context, nondestructive:
:g/replicant/z#.5|echo "=========="
" Confirm paranoia global :g actions:
:g/global delete with prompt/ if input("del line? " . line(".") . ":" . getline(".") . " y/[n] ")=="y" | delete | endif
" Delete a block range, sort of like paragrep, if you can determine start and end of blocks (must use slashes):
:g/^\s\+The SA/;/^ProdSp/d
" Non-inclusive delete. Only delete everything between these two lines:
:?firstword? 1,/lastword/ -1 d
" Chain two consecutive searches together, find the first 'peak info' appearing only AFTER (usually on next line) 'am0908':
/am0908/;/peak info
" Delete everything except these two strings:
:g!/SC04\/013-25\/60-24-01\|6ZM1234/d
" Insert specific lines of an external file into the top of your file.
:0r !head -n15 foo.txt
" Insert specific range of an external file at very top of your file.
:0r !awk'/start/,/end/{print}' foo.txt
" Delete everything prior to vim, keep the rest of the line:
:%s/.*\(vim.*\)/\1/gc
" Lowercase each letter in file (use u for uppercasing):
:%s/./\l&/gc
" Use L for lowercasing each line (use U for uppercasing):
:%s/.*/\l&/gc
" Lowercase or uppercase with \U all single line C-style comments:
:,$:s:\(/\*.*\*/\):\L\1:gc
" Lowercase a specific word (use \U for uppercasing):
:%s:\(LIST\):\L\1\E:gc
" or better
:%s:CODES:\L&\E:gc
" or shorter
:%s:CODES:\L&:gc
" Uppercase whole word
:0,$:s:foo:\U&:gc
" Restrict the pattern search and line marking to a stretch beginning three lines past the last previous line that starts with the string 'Exercises' and ending at the end of the file. +++ means previous 3 lines:
?^Exercises? +++ , $ g/foo/d
" Uppercase (a.k.a propcase rightcase titlecase smartcase) first letter of specific word:
:%s:upcaseme:\U&:cg
:0,$:s:foo:\u&:gc
" Uppercase first letter of all words:
:%s:[^ ]*:\L\u&:g
" or propcase all capitalized words as well:
:%s:\([A-Za-z]\)\([A-Za-z-]*\):\u\1\L\2:g
" Search across linebreaks:
/the\nword
" Search and replace across lines (e.g. replace Acme Distributors with Barrett...):
" First get instances NOT split over 2 lines... :%s/Acme Distributors/Barrett and Sons/g
" Then get those split across newlines... :g/Acme$/+ s/^Distributors/and Sons :g/^and Sons/- s/Acme$/Barrett
" Fix Perl comment on current line to start with a capital letter and end with a period:
:s:# \(.\):# \U\1: | s:$:\.:
" Turn line containing only a url into an HREF
:0,$:s:\(.*\):<a href=\1>\1</A>:gc
" Put angle brackets around an email address. E.g. <[email protected]> but not <[email protected]>
:0,$:s: \(\w\+@\w\+\.\w\+\)$: \<\1>:gc
" Write current line to file:
:. w foo.txt
" Write file to two different places (current dir and other) simultaneously:
:w | :w!/home/rheckel/tmp/%:t
" Quick date stamp on tail
:w %:t.YdS <---assumes my strftime vim map is available
" Insert date between stem and tail extension (still have to type the tail)
:w~/projects/%:t:r.oct08.sas
" Mainframe uses stem basename only (INCLUDE.sas goes as INCLUDE):
:!bfp % 'bqh0.pgm.lib(%:t:r)'
" Reorder a comma separated (CSV) file:
:%s:\([^,]*\),\([^,]*\),\([^,]*\),\(.*\):\1,\3 \4,\2:
" Then remove the spaces:
s/[ \t]*,[ \t]*/,/g
" Change really, really, really or really, really, really, really... to very
:%s/\(really \)\(really \)*/very /
" Insert a literal null (ascii 0). In insert mode:
Ctrl-v then 0
" If you know the column number which you want to act on (pipe here is vim magic not normal use of it):
" Replace columns 1 thru 70 with an X:
v70|rX
" or delete from current position to column 20
v20|d
" Find parts of a word like re or retu or return:
/\<re\%[turn]\>
" In code:
if wrd == "re" || wrd == "ret" || wrd == "retu" || wrd == "retur" ...do something... endif
" is now more cleanly represented as:
if match(wrd, "\\<re\\%[tur]\\>") > -1 ...do something... endif
" Alternate unicode foreign character digraph method (better if don't know the code):
:dig <---determine digraph's decimal code on (right side)
Ctrl-v 174 <---in insertmode e.g. copyright © symbol is 169
To do unicode, must do this first:
set encoding=utf-8
:se digraph
Then in insertmode (e.g copyright symbol):
C<BS>o <---Produces ©
s<BS>s <---Produces German ß
" Show where all tabs EOLs control hidden chars are on a whole a file:
:se list
" Scroll scrollbind windows together vertical default:
:se scb <---each window
" Horizontal scrollbind
:se sbo=hor
:se scb <---each window
" Change width of vertically split windows:
:vert resize 80
" Vim view all instances of this keyword anywhere in file. Think '[ is easier to reach on keyboard - lazy default show all'.
[I
" Recursively load files matching a pattern (like :e *.c but that doesn't work)
:args **/*.c
:argdo %s:'\\\\trpsawnv0312\\pucc:'C\:\\cygwin\\home\\rheckel\\projects\\datapost\\tmp:ge | update
" Bulk update substitute single quotes for double quotes in all open buffer files
:argdo g/libname/s/'/"/g | update
" Bulk update convert fully qualified path to SAS macrovariable in all open buffer files:
:argdo %s:C\:\\cygwin\\home\\bheckel\\VAIR_HFA:\&DIRROOT:ge | update
" Simple bulk update - must have used :args - the e flag in ge keeps vim quiet if no match (c confirm doesn't work-THERE IS NO CONFIRMATION), do a :vimgrep /foo/g **/*.sas first to verify what will change:
:argdo %s/foo/bar/ge | update
" Best search and replace in multiple files:
:args `grep -l foo *.sas` " open files
:argdo %s/foo/xxx/g " change w/o saving
:argdo update
" Remove blocks, paragraphs of text from a series of files. Edit multiple files:
$ vim -c 'argdo /begin/+1,/end/-1g/^/d | update' *.c
" Slow and mostly useless sed replacement unless we've loaded up :args instead of hardcoding foo.csv:
$ vim -c 'argdo set nomore | g!/-2008/d | update' foo.csv
" Count words word count (returns e.g. '4 matches on 3 lines'):
:%:s:replicant:&:gn
" After you've forgotten to check file permissions:
:w !sudo tee %
" Search find a word and move cursor offset to one or more char positions from match:
/myword/b <---cursor is on m (default -- beginning)
/myword/b+1 <---cursor is on y
/myword/e <---cursor is on d -- end of string (good for "delete thru this char": d /.../e )
/myword/e-2 <---cursor is on o -- end of string offset by minus 2
/myword/e+ <---cursor is on first char after myword -- end plus 1 char
" Insert date on current line:
!!date
" Display color syntax:
:so $VIMRUNTIME/syntax/colortest.vim
" Display current syntax groups (best):
:so $VIMRUNTIME/syntax/hitest.vim
" Non-standard regex: \= in Vim is ? in normal regex-land.
" Write a specific range to a new textfile using marks a and b:
:'a,'b w newfile.txt
" Regex if two or more: \{2,}
" Regex match the previous atom from 0 to m times: \{,m}
" Regex match the previous atom from 0 to m times but as little as possible i.e. non-greedy: \{-,m}
" Regex match the previous atom n to m times but as little as possible i.e. non-greedy: \{-n,m}
" Non greedy search, match 3 to 5 a's but prefer the shortest match: /a\{-3,5}
" Non-greedy Vim search (use :se hls to see the results better):
/a.*b <--- E.g. string axbxb greedy finds axbxb
/a.\{-}b <---non-greedy finds axb
" Better non-greedy (e.g. foo|bar|baz returns foo). Replace the first .* with [^|]*:
:,$:s:\([^|]*\)|.*:\1:gc
:%s/[^|]*|.*/xxx/gc
" For non-greedy .* becomes '[^']* to return 'foo' and 'bar' from this string:
" Match 'foo' and 'bar', including the quotes.
/'[^']*'
" Remove last column from a pipe delimited file:
:%s/.*\zs|.*//
" Modeline. Trailing ':' required for multiple set's. /* vim: set tw=72 ft=sas ff=unix: */ # vim: set list syntax=off foldmarker=#{{{,#}}} foldmethod=marker tw=78:
" Create a unique filename based on seconds since the Epoch:
$ vi foo`date +%s`.txt
" Find two blank empty lines:
/^$\n^$
" Simultaneously turn flip change Yes to 1 and No to 0 in one swoop:
:0,$:s:No:0:g|0,$:s:Yes:1:g
" Use calculator inside Vim:
:!echo 4+3+6 | bc
" Search for either string Yes or string No (alternation):
/\(Yes\)\|\(No\)
" Replace both strings Yes and No with foo:
:0,$:s:\(Yes\)\|\(No\):foo:gc
" Encrypt file for first time: :X then immediately :w (disable :set key=)
" Open file and place cursor at the search word ERROR or WARN:
vi -c '/^ERROR\|^WARN/' foo.txt
" Open file while copying and pasting (yanking and putting) the first line at the same time.
vi -c ':y | put' foo.txt
" Open file to last line of file, set textwidth:
vim -c 'set tw=68 et' + foo.txt
gvim -c 'set lines=20 columns=150'
" Easy quit:
vi -c 'map q :q!<CR>' foo.txt
vi -c 'map q :q!<CR>' -c 'map z noop' foo.txt
" Add non-standard help files to Vim Help 1- cd to the .txt 2- :helptags .
" To read in fewer than all lines use the shell:
:r !head -n30 foo.txt
" To print from GUI W32 Vim:
:hardcopy
" Halve, cut in half the current file:
:%norm jdd
" Simple canonical increment depending on my custom .vimrc fn. Ctrl-v highlight from your start num then:
vnoremap <C-A> :Inc<CR>
" Increment a left zero padded column of numbers (0000, 0100, 0200...), highlight them then:
:'<,'>Inc(100) <---Ctrl-a won't maintain the left zeros
" Increment a pattern ('pattern' is usually '@'). My .vimrc default is just highlight and :Incpat but to override defaults:
:1,4call IncPattern('p@','s0','i1') <--(p)attern, (s)tart at number, (i)ncrement by
" Yank the one single character that cursor is on:
yl
" Create fold zf, open fold zo, close all zx, delete zd, :set foldcolumn=2
" Open all folds zR (think 'release'). Close all folds zM (think 'mash').
" netrw most common keystroke cycling - s sort, i ls details, r reverse sort order
" netrw plugin if vim already open (beware there is NO file locking here):
:Nwrite "daeb rheckel Tistyb4p tmp/testing/junk2z"
:Nread "mf bqh0 Tistyb4p pgm.trash(junk)"
" Netrw using vim with ssh:
$ vi scp://rsh8680@tpsh005//opt/QCServer/A.05.00/svr/files/Inspec_Lot-0108.log # note no colon and double slash
" Debug shell script by doing an echo line below declaration:
:,$:s:\(export \(\w\+\).*\):\1echo '\2 ' \$\2:gc
" Debug perl script:
:,$:s:\(my \(\S\+\).*\):\1print '\2 ', \2;:gc
" Convert file to html using a .vim file:
:runtime! syntax/2html.vim
vi -c 'syntax off'
" nl(1) number line replacement
:g/^/exec "s/^/".strpart(line(".")." ", 0, 4)
" If vim -d is not available resort to: $ diff -ybB -W160
" Sort all non-blank lines from here down (alternative to visual mode & '=' ):
:.,/^$/-1!sort
" Count bytes and words to cursor:
g Ctrl-g
" DEPRECATED. Edit all .c files containing the word frame_counter:
vim `grep -l frame_counter *.c`
" Search Vim help:
:echo $VIMRUNTIME # e.g. /usr/share/vim/vim74
" Better (no quotes or slashes used here like vimgrep !), case insensitive, :cn to iterate results
:helpgrep holy-grail\c
:vim[grep] /holy-grail/ /usr/share/vim/vim70/doc/*
:vimgrep /\CSELECT.*into/j *.plsql " uppercase case sensitive search, j to not auto open first match
" then :cw or :cope to open quickfix results window
" Recursive search using star-star (slashes optional if not using a regex):
:vimgrep /select.*into/ **/*.plsql
" Alternatively on systems with grep(1) - faster but won't recurse:
:grep -i unexpected *.sas
" Search and replace all open buffers:
:bufdo %s/findme/changeme/gi
:bufdo update
" clear quickfix:
:cexpr []
" Canonical search across open buffers (then :cw)
:call setqflist([]) | silent bufdo grepadd! findme %
" Delete everything but the first 2 fields in a CSV
:%s:\(.\{-}\zs,\)\{2}.*::
" Canonical vim convert a file to HTML, opening the results in a new window:
:1,$TOhtml
" Crosshairs bullseye
:se cuc|se cul (or better :se cuc cul )
" View debug web page HTML/SAS Log output in Vim (using Vim instead of less)
w3m -dump 'http://rtpsawn321/sasweb/cgi-bin/broker.exe?_service=default&_program=LINKS.bobhmenu.sas&_debug=131&_server=rtpsawn321.corpnet1.com&_port=2738&_sessionid=HrYW7jQ7K52&pecORspec=Specification&menu=LACtlTblRd&Submit=++Read+LINKS+Specification+Table'|vim -R -c "se ft=saslog|map q :q<CR>" -
" Convert a comma delimited list to LIKE statements (TODO how to do IN('%ADVAIR%',...) ?
:,$:s:'\(\w\+\)[^,],:OR prod_nm LIKE '%\1%'^M:gc
" Swap tab-delimited field 5 with 4 position (use :se list to view these tabs):
,$:s:^\([^ ]*\) \([^ ]*\) \([^ ]*\) \([^ ]*\) \([^ ]*\) \(.*\):\1 \2 \3 \5 \4 \6 :gc
$ vim -u NONE -U NONE -N <---no .vimrc and plugins ('clean' VIM)
Ctl-] and Ctl-t to navigate Vim Help links
" Insert timestamp at end of file
map ,d Go<CR><C-R>=strftime("%Y-%m-%d")<CR>
" Run vim commands from shell command line without opening file:
vim -c "s/hello/goodbye cruel/" -c "wq" fun.txt
vi -c ':se nohls' -c ':se tw=50'
" Matches any line meeting the constraints: 1) contains anything (.*) followed by ObjectName 2) starts (^) with something which isn't 'import' (\(import\)\@!)
/.*ObjectName\&^\(import\)\@!
Finds line longer than 80 characters:
/\%>80v.\+
" Determine length of longest maximum line (custom fn in my .vimrc):
:Maxl
:call MaxLineLen(1)
:DirDiff . //trpsawnv0312/CODE/
:DirDiff $y/datapost/code $z/datapost/code " not to be confused with vimdiff
" dp to 'diff put' change to the other window, arrow keys to nav (double arrow up to de-syntax)
" do to 'diff obtain'
To synch DirDiff: s (in bottom pane with cursor ==>)
To synch DirDiff ranges of updates (internal DirDiff cmds like 'u' not working 2011-04-27):
:se nu
:5,42diffput
" Compare diff this vimdiff:
:vert diffsplit then switch to/open other buffer and :diffthis then force any changes :diffupdate when done reset :diffoff (:diffthis to restart vimdiff)
" vimdiff keymaps
do == :diffget
dp == :diffput
" Synch vimdiff diff whole file this window to the other:
:%diffput
" Run info(1) on word under cursor. Good demo of running an arbitrary command on the current word.
map ;p :exe ":!info ".expand("<cword>")<CR>
" Convert a tab-stopped file to a space-formatted file:
:set expandtab
:retab!
" Find all leading tabs and replace with spaces. Since every character in submatch(0) will be a tab we can replace each character with four spaces.
:%s/^\t*/\=substitute(submatch(0), ".", " ", "g")
" Put the tabs back over the 4 spaces:
:%s/^ \+/\=substitute(submatch(0), "....", "\t", "g")
:map :w :mksession! \| :write<CR>
" Do not forget to save folds etc.
:au BufWinLeave * mkview
" To avoid forgetting to mkview before exiting
:map :w :w\|mkview
" Insert a sequential list of numbers:
:put =range(11,15)
:for i in range(1,10) | put ='192.168.0.'.i | endfor
" Syntax highlight %THINGS% like that in a doc
syn match TODO "%\u\+%" containedIn=ALL
" Choose font. Font tester: Illegal1 = O0
:set guifont=*
:se guifont=Andale_Mono:h9
Omnicomplete default key combination using syntax files in insert mode C-X C-O
" Turn all open buffers into tabs
:tab ball
" This foldmethod doesn't modify the file:
:se fdm=manual
:setlocal foldmethod=marker
" Virtual edit (ctrl-v extended)
:se ve=all
" Open in new tab
:tab h quickref
" Delete every line except lines starting with a 6:
g/^[^6]/d
" Modify every 6 except those in column 1 (do not use 'c' switch!)
g/^[^6]/s/6/7/g
" My bc function map
vnoremap <C-P> "ey:call CalcBC()<CR>
:args **/*.sas | args cfg/* | args **/*.map
" Skip .vimrc:
vi -u NORC foo.txt
" Readonly:
vi -R foo.txt
" Verify runtime startup etc:
vi -V2
" On (K)eyword for help or man etc.:
K
" Then :cw[indow] to navigate results:
:helpgrep foo bar\c
" c-] and C-t ctags fwd back navigation:
:h quickref
" Show previous messages, errors, etc.:
:mes[sage]
" 1 if plugin is loaded (and 'let loaded_matchit=1' is in matchit.vim):
:echo loaded_matchit
" All plugins and .vimrc locations:
:scriptnames
" Test existence of Vim variables:
:echo has('gui_gtk3')
" Boolean checking (scripts mainly):
:echo &modifiable
" Is diff running:
if &diff
" Determine Vim's location:
:echo $VIMRUNTIME
" Check if any z* keys are mapped:
:map z
" Reload me:
:so $MYVIMRC
" View all current Vim variable values:
:let
" Chain two commands (unfortunately shortcircuits on 'Pattern not found'):
%s:<ExtractEnabled>1<\/ExtractEnabled>:<ExtractEnabled>0<\/ExtractEnabled>:g | :%s:<TransformEnabled>1<\/TransformEnabled>:<TransformEnabled>0<\/TransformEnabled>:g | :%s:<TrendEnabled>1<\/TrendEnabled>:<TrendEnabled>0<\/TrendEnabled>:g
" Chain global ex command regex
g!/10000000059062\|10000000060721/d
" Toggle HTML XML flags:
%s:<\(Extract\|Transform\)Enabled>1<:<\1Enabled>0<:gc
" Display search results with their line numbers:
:g/Line/#
" Highlight greenbar every other contiguous line:
map ,<Tab> :set hls<CR>/\\n.*\\n/<CR>
" Add more options to an existing vim setting:
set sessionoptions+=buffers
" Toggle vim setting:
nmap <silent> [[ :let &tabstop -= &tabstop > 1 ? 1 : 0<CR>
" Toggle a flag, creating it if it doesn't already exist:
let w:check_words = exists('w:check_words') ? !w:check_words : 1
" Sort file unique without external uniq:
:%sort u
" Force syntax coloring:
:sy off | se ft=sas | so $VIMRUNTIME/syntax/sas.vim
" Undo by time:
:earlier 5m
" Undo all file changes everything back to last write:
:ea 1f
:echom "Hello, " . "Vim concatenation world"
:mess
" List all files recursively:
:echo split(globpath('.', '**'), '\n')
" Very Magic parse convert disorganized list of numbers e.g. foo('1234', '5678')bar91011... into a CSV list:
:%s:\v\D+:,:g | :%s:^,\|,$::g
" Very Magic parse convert disorganized list of numbers e.g. foo('1234', '5678')bar91011... into a horizontal list:
:%s:\v\D+::g | g/^$/d
echon '.vimrc: unknown language: (' mylang ') so using default Commentout style'
" Vim fold folding
:se fdm=manual
" vim if then else:
if hostname() == 'yoniso' ... else ... endif
" Share ;w across network
scp [email protected]://mnt/nfs/home/bheckel/tmp/.vimxfer ~/tmp
" Copy this file to another host from vim (no warning on overwrite!):
:w scp://[email protected]/bin/%
# Share my vimxfer file across machines:
alias xfer='scp ~/tmp/.vimxfer b@talon3:tmp/.vimxfer'
# Set a shell variable:
WHEREISVIMRUNTIME=`vim -e -T dumb --cmd 'exe "set t_cm=\<C-M>"|echo $VIMRUNTIME|quit' | tr -d '\015'`
$ vim -e -T dumb --cmd 'exe "set t_cm=\<C-M>"|echo $VIMRUNTIME|quit'
" Keep only the first 12 characters, delete any characters after column position 12:
:s/^\(............\).*/\1/g
:s/\(.\{12\}\).*/\1/
" vim scp diff scp across networks using vim:
vi -d /Drugs/update_shortname_ds.sas scp://[email protected]//Drugs/update_shortname_ds.sas
" Find two strings in any order:
/.*reboot\&.*box
" Open Quickfix window:
:cw
" Vim array
let WORKBOXARRAY = [ 'L-ANA-BHECK', 'ZEBWL14H5','sas-01.taeb.com' ]
if matchstr(WORKBOXARRAY, THISBOX) == THISBOX
if $MYENVVAR =~ 'my vim regex$' ... endif
" Delete duplicate lines
:%s/^\(.*\)\(\n\1\)\+$/\1/
:mksession!
vi -S Session.vim
" Custom Save Session:
:mksession! ~/ses/48130
" Restore project folds, windows, etc. :mksession!:
vi -S ~/ses/48130
" Open file from command line at specific search place location:
vim -c '/tmm_targeted_list_refresh' ~/template_print.sas
-- Edit Postgres stored procedure in vim:
[email protected]:TAEBMART \ef analytics.tmm_client_build_config
nnoremap ,hdr :-1read ~/code/sas/Headertmplt.sas<CR>
" Use vim as a filter:
$ printf 'a\nb\nc\nb\n' | vim - -es --not-a-term +'g/b/norm gUUixx' +2 +'norm yy2p' '+%p' '+qa!' | tr x z
" Vimscript's wacky by-ref...:
let sorted_list = reverse(sort(unsorted_list))
" ...is almost always supposed to be:
let sorted_list = reverse(sort(copy(unsorted_list)))
/find start of line after this search pattern/+1
" Change filetype from SQL to PLSQL for certain filenames directories:
au BufRead,BufNewFile,BufEnter *RION-* set filetype=plsql
au BufRead * if @% =~ 'oneliners$'
if filereadable("~/tmp/SpecificFileExists") ...
vi -c 'map q :qa<CR>' ~/bin/allp
" Save vim snapshot poormans backup this file with vim occasionally to:
:silent! w!~/onedrive/misc/bkup/%:t
cmap xxo e \\\\sashq\\root\\dept\\mkc\\rion\\prod\\
cmap xxx e c:/Users/bheck/OneDrive\ -\ SAS/
" Buffer path search case insensitive:
:filter /\cfindme/ ls
xxVIMxx END:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:
xxSASxx START:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-: {{{1
proc contents data=sashelp._all_; run;
/* Missing value '.' always sort lower than char or num and ._ sorts lowest of all. A blank space ' ' is MISSING to SAS but not to SQL where it is a character. SAS special Missing Value (.A thru .Z) */
else if comment = 'refused to answer' then age = .A;...
if .z < labvalue < 3 then...
if .z < round(labvalue,0.0001) < 3.15 then...
/* Write all variables to the Log with "foo=" notation on one line: */
put _ALL_; /* print PDV to Log */
put 'WARNING: ' _ALL_;
put 'WAR' 'NING: ' _ALL_; /* better if you're searching a Log for real WARNINGs not a SOURCE or MPRINT: */
/* Write all variables to the Log with "foo=" notation on one line per var: */
put (_ALL_)(=)
/* Print all macrovariables. Use anywhere but can't combine to one %put: */
%put !!!; %put _USER_;
/* Macro -- no quotes! */
%put You find yourself in a maze of %upcase(twisty SAS passages) all alike;
/* In a DATA step -- quotes, no commas */
put 'fname is ' fname=;
put '!!!' _ALL_;
/* Writes specific variables to the Log. NO COMMAS. */
put varname1= varname2=;
/* Automatic concatenation: */
put 'here it is: ' varname1=;
/* Carriage return in output: */
put;
put '0D'x; /* s/b the same */
put '0D0A'x; /* carriage return line feed */
/* Runaway GUI SAS killer: */
/* '; * "; */; %mend; quit; run;
;*';*";*/;quit;run; /*Quote and Comment Killer*/
/* Free up space - delete datasets */
proc datasets library=WORK; kill; QUIT; /* !not just RUN; */
proc datasets NOlist library=l; delete patmod_all_cha rxfilldata_all_cha; run; quit;
/* Column input with some missing data -- use TRUNCOVER List input with some missing data at the rightmost edge -- use MISSOVER to keep SAS from trying the next line (e.g. when you're not using @@ and want it to keep going) "SAS went to a new line when" */
/* Print list describe all paths to SAS libname libraries: */
libname _ALL_ list;
/* Clear delete libnames: */
libname _ALL_ clear;
libname L clear /* only one libname allowed! */
/* Determine where the WORK temp library is located on your system: */
libname WORK list;
/* Determine where the WORK temp library is located on your system via macro: */
%let workpath=%sysfunc(pathname(work));
/* Use more than one library, look in best first, then justok if not found: */
libname mylib (best justok);
/* libname concatenation. Works on z/OS too. Only a WARNING: for idontexist/ */
libname CONCAT ('c:/temp' 'c:/cygwin/tmp/' 'c:/idontexist');
SAS debugger e.g. data foo / DEBUG; ...; run;
'07jul00'D <---SAS date constant
'07JUL2000'D <---SAS date constant
'04:15'T <---SAS time constant (seconds since midnight 0-86400)
'04:15:66pm'T <---SAS time constant (seconds since midnight 0-86400)
'07jul2000:04:15:00'DT <---SAS datetime constant
SAS Functions work *within* an observation. SAS Procedures work *across* observations.
/* Increment in macro. Like yr++ */
%let YR1 = 2002; %let YR2 = %eval(&YR1+1);
/* Convert macrovariable (always string) to numeric: */
data _null_; age=input(symget('age'),12.); run;
%macro m;data _null_; age=input("&age"),12.); put age=; run;%mend;%m; /* FAIL */
/* SAS X command (ok in open code): */
x 'c:/util/vim/vim61/gvim.exe -c "set winsize=100 20" out.dat';
x 'psql -h db-dev-01.twa.taeb.com TAEBMART -c "\copy bobtable from ''/mnt/nfs/home/bheckel/t.txt'' (delimiter '','');"';
/* Canonical dice generate random whole number between range 1 and 6 (must use ceil to get the 1): */
randomnum = ceil(ranuni(0) * 6);
/* Generate random number floating point number between 100 and 123: */
randomnum = ranuni(-1)*23 + 100;
/* Generate random number between 0 and 1 (but not 0 or 1): */
randomnum = round(ranuni(-1));
/* Shuffle a ds: */
data t; set t; shuffle=ranuni(0); run; proc sort; by shuffle; run;
/* Interactive SAS on OS/390 (from TSO command line): */
==> sas options('dms yearcutoff=1905')
/* Using 1920 default: 00...19 becomes 2000...2019 */
//* Use your own SAS System Options in JCL:
//STEP1 EXEC SAS,CONFIG='BQH0.PGM.DEV(MYCONFIG)',TIME=100,
// OPTIONS='MEMSIZE=0'
/* Set option from command line: */
$ /sas/sashome/SASFoundation/9.4/sas -memsize 0 t.sas /* t.sas is proc options option=MEMSIZE value; run; */
/* Sets the auto variable myfname, not the keyword FILENAME, to the physical name of the currently opened file! */
infile IN FILENAME=myfname; /* lvalue assigns rvalue ! */
/* SAS hexadecimal tab '09'x or '05'x or '3132,3334'x */
put aprclass '09'x '09'x APR_Count;
/* It's an alphabetical character isalpha: */
if ship GE 'a' and ship LE 'z' then delete;
/* It's a numeric character isnum: */
if indx GE '0' and indx LE '9' then delete;
/* Keep only numbers from a mixed CHAR variable: */
isnum = verify(compress(storeid), '.0123456789'); if isnum eq 0 then put "pure numerical";
/* Distributive range input statement: */
input @166 (r1-r15) ($CHAR1.);
input @166 (c1-c15) (:$1.);
/* Distributive put statement */
put (ymd_no_ampm mdy_ampm ymd_ampm mdy_noampm)(= DATETIME18.);
put one_two= / trip= / (cat1-cat4)(= /); /* slash insert newlines */
/* Distributive length statement */
length foo $2 car1-car4 $9;
/* %global is distributive */
%global foo bar;
/* Super input statement uses the data itself to determine column position */
input @'IP Address' n1 n2 n3 n4 3.;
/* Move cursor one column to the left, put a backspace, to squeeze colon against word: */
put @1 myname +(-1)":" @30 myvalue;
/* Multiple datasets on the set statement: */
data work.all; set %do j=1 %to 3; work.tmp&j %end; ; run;
/* Get current year date: */
call symput('THISYR', substr(put("&sysdate9"d,mmddyy10.),7,4));
/* 1_______today into epoch num_______ */
%let thisyr=%sysfunc(putn(%sysfunc(inputn(&sysdate9,date9.)),year.));
/* 2______________.................................._______ */
/* format epoch num to date format */
call symputx('THISYR', put(intnx('year', "&SYSDATE"D, 0, 'B'),YEAR.), L);
%let dtnum=%sysfunc(dhms('01JAN60'd,0,70,0)); /* 70 converts to 1 min 10 seconds */
%let dtformatted=%sysfunc(putn(&dtnum,datetime.)); /* 01JAN60:01:10:00 */
/* Increment a symput generated macrovariable: */
call symput('RUNME'||compress(put(_N_,5.)), executemacro);
/* Wild equal colon -- same as using LIKE 'mormer%' in SQL: */
set t(where=(region in:('As')));
if foo =: 'mormer';
/* Uppercase a macrovariable: */
%let the_type=%upcase(&the_type);
/* Mainframe filename */
filename OUT "DWJ.DCFET03.D04NOV03" DISP=NEW UNIT=TEMP LRECL=229 BLKSIZE=229 RECFM=FB;
/* Fixed length file. Pads to 70. */
filename f 'c:/temp/foo1' lrecl=70 recfm=f;
/* Variable length file. No padding. */
filename f 'c:/temp/foo2' lrecl=70 recfm=v;
/* Today's SAS epoch date (range is 1582 - 20000 AD). Convert unix to SAS epoch date: */
$ date +%s |awk '{d=int($1/86400+3653)} END {print d}'
/* Left zero pad a number: */
zerocert=put(certificate, Z6.);
select distinct put(zipcode,z5.) as zipcode ...
/* Jumpstart proc report then tweak autogenerated code: */
proc report data=sashelp.class LIST NOEXEC; run;
/* Reorder the variables in a dataset (alternatively use proc report): */
retain first second third;
/* Create a C-like null terminated string: */
substr(mystr, mylen+1) = '00'x
/* Name of this currently running SAS program file: (like $0 in shell): */
%put basename only of currently running program: &SYSPROCESSNAME
%put NOTE: fully qualified name of the currently this program running: %let thispgm=%sysfunc(getoption(SYSIN));
/* CLASS categorical variables: almost always stored as chars, identify classes (discrete categories) on which calculations are done. E.g. gender, country, state, zip. */
/* VAR analysis variables: numbers, usually continuous, appropriate for calculating averages, sums, etc. E.g. salary, number of orders. */
/* Pick off 'MOR' from the suffix */
%let FN=BF19.FIX0342.MORMER1; %let EVT=%substr(%scan(&FN, 3, '.'), 1, 3);
/* SAS exponentiation */
x = 2**3;
/* Syntax check program (compile) without running or overwriting files (for debugging): */
options obs=0 NOreplace;
/* Syntax check datastep (compile) without running or overwriting files (for debugging): */
run cancel;
/* Do to first obs: */
if _N_ eq 1 then put 'data step has BEGUN EXECUTING once';
/* Do to last obs: */
set l.sumventolin01a (obs=10) end=e; if e then put 'footer';
/* Caution: _N_ is only counting begun iterations of the implied loop of the dataset, NOT the observations */
/* Subsetting IFs can appear only in DATA steps but WHERE statements can appear in DATA or PROC steps */
/* Run SAS from commandline without my ~/bin/sasrun */
$ sas -sysin t.sas; cat t.log
$ sas -sysin t.sas; vim -o -c '/^ERROR.*:\|^WARNING:/' t.log t.lst
" Run a .sas from Vim on an alien box
:!/cygdrive/c/Program\ Files\/SAS\ Instititute/SAS/V8/sas.exe -sysin %
:!/cygdrive/c/Program\ Files\/SAS\ Instititute/SAS/V8/sas.exe -sysin % -altlog %.log -altprint %.lst
/* Run Version 9 V9 SAS from commandline */
c:/PROGRA~1/SAS/SASFoundation/9.2/sas.exe -sysin t.sas && vi *.l??
/* String foo is available in &SYSPARM */
$ c:/PROGRA~1/SASINS~1/SAS/V8/sas.exe -nosplash -sysin t.sas -altlog Apr.log -sysparm foo
/* Passing a comma separated list will require e.g.
* %let samplist=%scan(%bquote(&SYSPARM), 2, '_');
* in the code:
*/
$ date;c:/PROGRA~1/SASINS~1/SAS/V8/sas.exe -sysin indsumresCI.sas -altlog 01.log -sysparm 01_231973,231591,231476
/* If you can't edit the command line, use these in start/end of the code to save Log and List (NEW to avoid append): */
proc printto LOG="D:\foo.log" NEW PRINT="D:\foo.lst" NEW; run; ...code... proc printto;run;
/* Keep GUI open during the run. Instead of -sysin */
c:/PROGRA~1/SASINS~1/SAS/V8/sas.exe -autoexec "\\trpsawnv0312\pucc\Serevent_Diskus\CODE\0_MAIN_Serevent_Diskus.sas" -sysparm "\\trpsawnv0312\pucc\Serevent_Diskus\CODE"
/* Suppress discard SAS List .lst */
c:\PROGRA~1\SASINS~1\SAS\V8\sas.exe -sysin t.sas -log t.log -NOterminal -NOprint
/* Communicate with SAS in a Windows .bat batchfile */
set sasexe="D:\SAS Institute\SAS\V8\sas.exe"
set dpv2root=E:\DataPost
set sascode=%dpv2root%\code
%sasexe% -WORK 'c:\temp\sas' -nosplash -sysin %sascode%\DataPost_Transform.sas -log %sascode%\DataPost_Transform.log -print %sascode%\DataPost_Transform.lst -sysparm "%dpv2root%"
# Cygwin quick dataset check:
echo 'options ls=180;proc contents data=?;run;' >| t$$.sas; C:/PROGRA~1/SASHome/SASFoundation/9.3/sas.exe -sysin t$$.sas && cat t$$.lst && rm t$$.???
echo "options ps=max;libname l '//Rtpdsn032/DataPostArchive/Ventolin_HFA/OUTPUT_COMPILED_DATA' compress=yes; proc freq data=l.ven60_analytical_individuals;table mfg_batch test;run;" >| u:/tmp/t.sas && c:/PROGRA~1/SASINS~1/SAS/V8/sas.exe -sysin 'u:\tmp\t.sas' -log 'u:\tmp\t.log' -print 'u:\tmp\t.lst'; cat 'u:\tmp\t.lst'
/* Describe option settings in effect: (also sr ~/code/sas/options.cmdl.sas linesize) */
proc options option=&SYSPARM define value; run;
format vs informat: Whereas a SAS format converts an underlying data representation to a visual representation, an informat converts a visual representation into an underlying data representation. Formats modify the external representation of a value (preexisting in a ds). Informats convert raw data into SAS representations (to be put in a ds).
/* Current dataset macrovariable formatted to "LIBRARY DSNAME" */
&SYSDSN
/* Print quotes around a variable, in this case, myvar */
put "!!! found quoted " myvar $QUOTE.;
/* Check if a file has a SAS extension */
if index(lowcase(myfile),'.sas') > 0; /* true */
if scan(lowcase(myfile),-1,'.') eq 'sas'
/* Portability -- Use this JCL for SAS filename on MF: */
//IN DD DISP=SHR,DSN=BF19.MOX0401.NATMER
/* vs. this JCL-less method on the PC via Connect: */
filename IN 'BF19.MOX0401.NATMER' DISP=SHR;
/* Include code plus display source w/o an options statment (%include is synchronous): */
%include 'tabdelim.sas' / SOURCE2;
/* Find max using a SAS range: */
retain hi; hi=max(hi, DatastepVarWeWantMaxFrom);
/* Find max using a SAS range: */
if max(of one1-one3) < 5 then ...
/* SAS array declare and initialize */
array starr{*} $2 st1-st57 ('AL', 'AK', 'AR', 'AZ', 'CA', 'CO');
/* SAS array access */
do i=1 to dim(starr); otherarr{i} = starr{i}; end;
/* Get the HOME environment variables: */
%let myhome=%sysget(HOME); %put _all_; %let sasroot=%sysget(SASROOT); %put &=SASROOT;
%put %sysget(SASHOME) %sysget(SASROOT);
/* Substring (if argument might contain a special character or mnemonic operator use %qsubstr()) */
%put %substr(2168, 3, 2);
data _null_; x=substr('2168', 3, 2); put x=; run;
/* Good demo sample template dataset: */
proc print data=SASHELP.shoes (obs=10); var region stores sales returns; run;
/* Macro with parameters parms: */
%macro Foo(bar, baz); %put &bar and &baz; %mend; %Foo(test ing, me);
%macro Foo(bar=, baz=); %put &bar and &baz; %mend; %Foo(bar=test ing, baz=me);
/* Named macro call with good default parameters: */
%macro Foo(data=_LAST_, by=, vars=, out=_DATA_);
/* Preserve leading whitespace ($3. would not) */
input foo $CHAR3.;
/* Suppress any input errors in SAS Log and keep _ERROR_=0 */
input name $8. number ??;
/* Operating system specific option: */
%macro os_detect; %if &SYSSCP eq OS %then %str(options NOs99nomig;); %mend;
%macro os_detect; %if "&SYSSCP" eq "LIN X64" %then %put Unix; %mend;
/* Thin out cleanout SAS Log, can use \| to get >1 line at a time */
:g/\s*SYMB\|\s*MLOG\|\d\+\s*THE SAS/d
/* Small shrink dataset to 5% random sample sampling for debugging huge ds to subset dataset (different result each run): */
data t2; set t; if ranuni(0) <= .05; run;