-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbash_shell_func.sh
More file actions
1415 lines (1269 loc) · 43.1 KB
/
bash_shell_func.sh
File metadata and controls
1415 lines (1269 loc) · 43.1 KB
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
#!/bin/bash
## Source base functions
source "$(dirname "${BASH_SOURCE[0]}")/bash_base_func.sh"
## Debugging
bash_strace() { echo exit | strace bash -li |& grep '^open'; }
## Bash prompts
prompt_venv_prefix() { printf '%s' "$PS1" | grep -Eo '^[[:space:]]*\([^\(\)]*\)[[:space:]]+'; }
# no colors
#prompt_dname() { export PS1="$(prompt_venv_prefix)\W \$ "; }
#prompt_dfull() { export PS1="$(prompt_venv_prefix)\w \$ "; }
#prompt_short() { export PS1="$(prompt_venv_prefix)[\u@\h:\W]\$ "; }
#prompt_med() { export PS1="$(prompt_venv_prefix)[\u@\h:\w]\$ "; }
#prompt_long() { export PS1="$(prompt_venv_prefix)[\u@\H:\w]\$ "; }
#prompt_reset() { export PS1="[\u@\h:\w]\$ "; }
# colors
prompt_dname() { export PS1="$(prompt_venv_prefix)\[\033[01;34m\]\W\[\033[00m\] \$ "; }
prompt_dfull() { export PS1="$(prompt_venv_prefix)\[\033[01;34m\]\w\[\033[00m\] \$ "; }
prompt_short() { export PS1="$(prompt_venv_prefix)[\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\W\[\033[00m\]]\$ "; }
prompt_med() { export PS1="$(prompt_venv_prefix)[\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]]\$ "; }
prompt_long() { export PS1="$(prompt_venv_prefix)[\[\033[01;32m\]\u@\H\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]]\$ "; }
prompt_reset() { export PS1="[\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]]\$ "; }
ccmd() {
read -r -e -p "$ " cmd
history -s "$cmd"
eval "$cmd"
}
## Colorize output streams
color() { "$@" 2> >(sed $'s,.*,\e[31m&\e[m,'>&2); }
## String manipulation
line2space() {
local str result
if [[ -p /dev/stdin ]]; then
str=$(cat)
else
str="$1"
fi
result=$(string_strip "$str" | tr '\n' ' ')
echo "$result"
}
space2line() { tr ' ' '\n'; }
line2csstring() {
local result=$(xargs printf "'%s',")
result=$(string_rstrip "$result" ',')
echo "$result"
}
line2csstring_alt() {
tr '\n' ',' | sed -r -e "s|\s||g" -e "s|^,*|'|" -e "s|,*$|'|" -e "s|,+|,|g" -e "s|,|','|g"
}
# Replace all instances of a string with another string.
#
# Takes a piped in string (any number of lines) and outputs the
# the same string with all instances of a specified string replaced
# with another provided string.
# This is a simple wrapper of the `sed` command.
#
# $1 - First string, to be searched for and replaced.
# $2 - Second string, to replace the first string with.
#
# Examples
#
# echo "dog cat dog cat" | string_replace 'cat' 'pig'
# => "dog pig dog pig"
#
# Prints to stdout the string with replacements made.
#
# Returns the exit code of the wrapped `sed` command.
string_replace() { sed "s|${1}|${2}|g"; }
# Prepend a string to the beginning of each input line.
#
# Takes a piped in string (any number of lines) and outputs the
# the same string with the provided string affixed to the beginning
# of each input line.
# This is a simple wrapper of the `sed` command.
#
# $1 - The string to be prepended to each input line.
#
# Examples
#
# echo "world" | string_prepend "hello "
# => "hello world"
#
# Prints to stdout the string with prepends added.
#
# Returns the exit code of the wrapped `sed` command.
string_prepend() { sed "s|^|${1}|"; }
# Append a string to the end of each input line.
#
# Takes a piped in string (any number of lines) and outputs the
# the same string with the provided string affixed to the end
# of each input line.
# This is a simple wrapper of the `sed` command.
#
# $1 - The string to be appended to each input line.
#
# Examples
#
# echo "hello" | string_append " world"
# => "hello world"
#
# Prints to stdout the string with appends added.
#
# Returns the exit code of the wrapped `sed` command.
string_append() { sed "s|$|${1}|"; }
## Command-line argument manipulation
# Run `eval echo` on the provided arguments.
#
# Takes in a string of arguments, provided either as function arguments
# or piped in on a single line, and runs them through
# `eval "echo <arguments>"` so that globs can be expanded.
#
# $@ - Arguments provided to `echo` command.
#
# Examples
#
# ls *.txt
# ./test1.txt ./test2.txt ./test3.txt
#
# echoeval "*.txt"
# => test1.txt test2.txt test3.txt
#
# echo "*.txt" | echoeval
# => test1.txt test2.txt test3.txt
#
# Prints to stdout the result of the `echo` command`.
#
# Returns the exit code of the `echo` command.
echoeval() {
local echo_args
if [[ -p /dev/stdin ]]; then
IFS= read -r echo_args
else
echo_args="$*"
fi
eval "echo ${echo_args}"
}
tokentx() {
local tx="$1"
local token_arr=()
local token_tx_arr=()
local token_delim='\n'
local token
while IFS= read -r token; do
token_arr+=( "$token" )
done
if (( ${#token_arr[@]} == 1 )); then
token_delim=' '
IFS="$token_delim" read -r -a token_arr <<< "${token_arr[0]}"
fi
local token_tx
for token in "${token_arr[@]}"; do
token_tx=${tx//'%'/${token}}
token_tx_arr+=( "$token_tx" )
done
printf "%s${token_delim}" "${token_tx_arr[@]}"
}
layz() {
local cmd_arr_in cmd_arr_out
local arg_idx rep_idx
local arg_out arg_rep
local cmd_out debug arg_opt
debug=false
if [[ $1 == -* ]]; then
arg_opt=$(echo "$1" | sed -r 's|\-+(.*)|\1|')
if [ "$arg_opt" = 'db' ] || [ "$arg_opt" = 'debug' ] || [ "$arg_opt" = 'dr' ] || [ "$arg_opt" = 'dryrun' ]; then
debug=true
shift
fi
fi
cmd_arr_in=("$@")
cmd_arr_out=()
for arg_idx in "${!cmd_arr_in[@]}"; do
arg_out="${cmd_arr_in[$arg_idx]}"
for rep_idx in "${!cmd_arr_in[@]}"; do
if (( rep_idx < arg_idx )); then
arg_rep="${cmd_arr_out[$rep_idx]}"
else
arg_rep="${cmd_arr_in[$rep_idx]}"
fi
arg_out=$(echo "$arg_out" | sed -r "s|%${rep_idx}([^0-9]\|$)|${arg_rep}\1|g")
done
cmd_arr_out+=( "$arg_out" )
done
cmd_out="${cmd_arr_out[*]}"
if [ "$debug" = true ]; then
echo "$cmd_out"
else
$cmd_out
fi
}
timestmap2datestr() {
sed -r 's|([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})|\1-\2-\3 \4:\5:\6|'
}
## File operations
# Link file(s) if possible, otherwise copy.
#
# First executes `ln -f <arguments>` with all provided arguments appended
# If the return code of that command is non-zero, executes `cp <arguments>`
# using the same set of provided arguments.
#
# $@ - Arguments provided to `ln -f` or `cp` to perform link or copy.
#
# Examples
#
# link_or_copy "src_file.txt" "dst_file.txt"
#
# Returns the non-zero exit code of `cp` command if both `ln -f` and `cp`
# are unsuccessful (non-zero exit code), or 0 otherwise.
link_or_copy() {
if ! ln -f "$@"; then
cp "$@"
fi
}
conda_activate() {
local env_name="$(basename "$(abspath .)")"
conda activate "$env_name"
}
pixi_create() {
local env_name
if [ -n "$1" ]; then
env_name="$1"
else
env_name="$(basename "$(abspath .)")"
fi
if [ -z "$env_name" ]; then
echo "Error: local var 'env_name' is empty" >/dev/null
return
fi
local env_path="${HOME}/mini_pixi_envs/${env_name}"
local pixi_dir=".pixi"
set -x
mkdir -p "$env_path"
ln -sTf "$env_path" "$pixi_dir"
set +x
}
pixi_remove() {
local env_name
if [ -n "$1" ]; then
env_name="$1"
else
env_name="$(basename "$(abspath .)")"
fi
if [ -z "$env_name" ]; then
echo "Error: local var 'env_name' is empty" >/dev/null
return
fi
set -x
local env_path="${HOME}/mini_pixi_envs/${env_name}"
local pixi_dir=".pixi"
rm -rf "$env_path"
rm -f "$pixi_dir"
set +x
}
absymlink_defunct() {
local arg_arr arg
arg_arr=()
while (( $# > 0 )); do
arg="$1"
if ! [[ $arg == -* ]]; then
arg=$(readlink -f "$arg")
fi
arg_arr+=( "$arg" )
shift
done
ln -s "${arg_arr[@]}"
}
mv_and_absymlink() {
local src_arr=()
local dst=''
local mv_args_arr=()
local dst_dir_exists
local dryrun=false
if (( $# == 2 )); then
src_arr+=( "$1" )
dst="$2"
if [ -d "$dst" ]; then
dst_dir_exists=true
else
dst_dir_exists=false
fi
else
dst_dir_exists=true
local arg arg_opt
while (( $# )); do
arg="$1"
if [ "$(string_startswith "$arg" '-')" = true ]; then
arg_opt=$(string_lstrip "$arg" '-')
if [ "$(itemOneOf "$arg_opt" 'dr' 'dryrun' 'db' 'debug')" = true ]; then
dryrun=true
shift; continue
elif [ "$arg" == '-t' ]; then
dst="$2"; shift
else
mv_args_arr+=( "$arg" )
fi
elif (( $# == 1 )) && [ -z "$dst" ]; then
dst="$arg"
else
src_arr+=( "$arg" )
fi
shift
done
fi
local mv_opt_args="${mv_args_arr[*]+${mv_args_arr[*]}}"
local dryrun_arg
if [ "$dryrun" = true ]; then
dryrun_arg='-dryrun'
else
dryrun_arg=''
fi
local src dst_path
for src in "${src_arr[@]}"; do
mv_cmd="mv ${mv_opt_args} \"${src}\" \"${dst}\""
if [ "$dryrun" = true ]; then
echo "$mv_cmd"
else
eval "$mv_cmd"
fi
if [ "$dst_dir_exists" = false ]; then
dst_path="$dst"
else
dst_path="${dst%/}/$(basename "$src")"
fi
absymlink ${dryrun_arg} "$dst_path" "${src%/}"
done
}
touch_all() {
echo "Will recursively search through argument directories and touch all files within"
if (( $# == 0 )); then
echo "Usage: touch_all path1 path2 ... pathN"
return
fi
while (( $# > 0 )); do
echo "Touching files in: ${1}"
find "$1" -type f -exec touch {} +
shift
done
echo "Done!"
}
trashem() {
# Utilizes trash-cli: https://github.com/andreafrancia/trash-cli
if (( $# == 0 )); then
echo "Usage: trashem PATH... ['find' OPTION]..."
return
fi
path_arr=()
while (( $# > 0 )); do
if [[ $1 == -* ]]; then
break
fi
path_arr+=( "$(abspath "${1%/}")" )
shift
done
if (( ${#path_arr[@]} == 0 )); then
echo "Usage: PATH... ['find' OPTION]..."
return
fi
for path in "${path_arr[@]}"; do
echo "Trashing: ${path}"
stat "$path" > "${path}.removed.stat"
find "$path" "$@" | sort > "${path}.removed.contents"
trash-put "$path"
done
}
## Read inputs
headtail() {
perl -e 'my $size = '$1'; my @buf = (); while (<>) { print if $. <= $size; push(@buf, $_); if ( @buf > $size ) { shift(@buf); } } print "------\n"; print @buf;'
}
get_csv_cols() {
:
}
wread() {
IFS= read -r "$@"
}
wread0() {
IFS= read -r -d '' "$@"
}
SHELL_UTILS_READ_CSV_IP=false
# Read CSV file field values line by line.
#
# This method is a substitute for the standard `read` command used to
# more easily parse one or more field values from a CSV file. In each
# call to `read_csv`, variables are set in the current shell to reflect
# the values of the indicated field names at the last line read by an
# internal call to the `read` command on the CSV file. The names of
# these variables are the same as the field names, and are meant to be
# used directly.
# The (non-local) variables containing the CSV field values are
# created and modified through `eval`. Once the final line in the CSV
# file has been read, the variables are unset through
# `eval "unset <field_name>"`.
#
# $1 - Comma-separated list of field names whose values will be read.
#
# Examples
#
# line_num=0
# while read_csv field1,field2; do
# ((line_num++))
# echo "line ${line_num}: field1=${field1}, field2=${field2}"
# done < "./example.csv"
# => "line 1: field1=some_value1, field2=other_value1"
# => "line 2: field1=some_value2, field2=other_value2"
# => ...
#
# Returns the exit code of the `read` command used to parse the last
# line read from the CSV file.
read_csv() {
local get_fields="$1"
local csv_delim=','
if (( $# >= 2 )); then
csv_delim="$2"
fi
local read_status IFS
local csv_line csv_line_arr
csv_line=''
if [ "$SHELL_UTILS_READ_CSV_IP" = false ]; then
SHELL_UTILS_READ_CSV_GET_FIELDS_NAME_ARR=()
SHELL_UTILS_READ_CSV_GET_FIELDS_IDX_ARR=()
local header_line get_fields_arr header_fields_arr
IFS= read -r header_line
read_status=$?
if (( read_status != 0 )); then return "$read_status"; fi
IFS="$csv_delim" read -ra get_fields_arr <<< "$get_fields"
IFS="$csv_delim" read -ra header_fields_arr <<< "$header_line"
local get_field_idx field_name field_idx
local get_field_in_header=false
local first_missing_get_field=''
for get_field_idx in "${!get_fields_arr[@]}"; do
field_name="${get_fields_arr[${get_field_idx}]}"
eval "unset ${field_name}"
field_idx=$(indexOf "$field_name" "${header_fields_arr[@]}")
if (( field_idx == -1 )) && [ -z "$first_missing_get_field" ]; then
first_missing_get_field="$field_name"
fi
if (( field_idx == -1 )) && [ "$get_field_in_header" = false ]; then
field_idx="$get_field_idx"
elif (( field_idx == -1 )) || [ -n "$first_missing_get_field" ]; then
echo "ERROR: Cannot find field name '${first_missing_get_field}' in CSV header" >&2
unset SHELL_UTILS_READ_CSV_GET_FIELDS_NAME_ARR
unset SHELL_UTILS_READ_CSV_GET_FIELDS_IDX_ARR
return 1
else
get_field_in_header=true
fi
SHELL_UTILS_READ_CSV_GET_FIELDS_NAME_ARR+=( "$field_name" )
SHELL_UTILS_READ_CSV_GET_FIELDS_IDX_ARR+=( "$field_idx" )
done
if [ -n "$first_missing_get_field" ]; then
# No 'get fields' match strings in first row of CSV,
# so assume the CSV has no header and match order of
# 'get fields' to the order of CSV columns.
csv_line="$header_line"
csv_line_arr=("${header_fields_arr[@]}")
fi
SHELL_UTILS_READ_CSV_IP=true
fi
if [ -z "$csv_line" ]; then
IFS= read -r csv_line
read_status=$?
if (( read_status != 0 )); then
if [ -n "$csv_line" ]; then
# This is likely the case where we're reading
# the last line of input and it doesn't have
# a trailing newline so 'read' has a nonzero
# exit status. We still want to parse this line.
read_status=0
else
SHELL_UTILS_READ_CSV_IP=false
unset SHELL_UTILS_READ_CSV_GET_FIELDS_NAME_ARR
unset SHELL_UTILS_READ_CSV_GET_FIELDS_IDX_ARR
local field_name
for field_name in "${SHELL_UTILS_READ_CSV_GET_FIELDS_NAME_ARR[@]}"; do
eval "unset ${field_name}"
done
return "$read_status"
fi
fi
IFS="$csv_delim" read -ra csv_line_arr <<< "$csv_line"
fi
local i field_name field_idx field_val
for i in "${!SHELL_UTILS_READ_CSV_GET_FIELDS_NAME_ARR[@]}"; do
field_name="${SHELL_UTILS_READ_CSV_GET_FIELDS_NAME_ARR[$i]}"
field_idx="${SHELL_UTILS_READ_CSV_GET_FIELDS_IDX_ARR[$i]}"
field_val="${csv_line_arr[$field_idx]}"
eval "${field_name}=\"${field_val}\""
done
return "$read_status"
}
## Distill information
stat_sec() {
stat --format '%Y' "$@"
}
du_k() { du --block-size=1K "$@" | awk '{print $1}'; }
du_m() { du --block-size=1M "$@" | awk '{print $1}'; }
du_g() { du --block-size=1G "$@" | awk '{print $1}'; }
du_t() { du --block-size=1T "$@" | awk '{print $1}'; }
uniq_preserve_order() {
awk '!visited[$0]++'
}
smart_sort() {
# Example: ls WV01_20140716_102001003208CC00_102001003223F500_2m_lsf_v040310/*_meta.txt | smart_sort '_seg([0-9]+)_' '_seg%04d_'
local substr_pattern_capture_sort_group="$1"
local substr_format_expand_sort_group="$2"
local substr_pattern=$(echo "$substr_pattern_capture_sort_group" | tr -d '()')
sed -r -e "s|^(.*)(${substr_pattern})(.*)$|\1\2\3,\2|" -e "s|${substr_pattern_capture_sort_group}|\$(printf '${substr_format_expand_sort_group}' \1)|" \
| while IFS= read -r line; do eval echo "$line"; done \
| sort | sed -r "s|^(.*)(${substr_pattern})(.*),(${substr_pattern})$|\1\4\3|"
}
wc_nlines() {
process_items 'wc -l' false true 0 "$@" | awk '{print $1}'
}
count_items() {
awk '{item_count_dict[$0]++} END {for (item in item_count_dict) printf "%5s <-- %s\n", item_count_dict[item], item}' | sort -k3
}
count_by_date() {
grep -Eo '(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+[0-9]+' | awk '{date_count_dict[$0]++} END {for (date in date_count_dict) printf "%s : %5s\n", date, date_count_dict[date]}' | sort
}
count_by_month() {
grep -Eo '(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+[0-9]+' | awk '{date_count_dict[$1]++} END {for (date in date_count_dict) printf "%s : %5s\n", date, date_count_dict[date]}' | sort
}
count_by_date_with_ex() {
grep -Eo '(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+[0-9]+.*$' | awk '{date=sprintf("%s %2s", $1, $2); date_count_dict[date]++; date_ex_dict[date]=$0} END {for (date in date_count_dict) printf "%s : %5s : %s\n", date, date_count_dict[date], date_ex_dict[date]}' | sort
}
count_by_month_with_ex() {
grep -Eo '(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+[0-9]+.*$' | awk '{date=$1; date_count_dict[date]++; date_ex_dict[date]=$0} END {for (date in date_count_dict) printf "%s : %5s : %s\n", date, date_count_dict[date], date_ex_dict[date]}' | sort
}
strip_cols() {
local col_delim_in=' '
local col_delim_out=' '
if (( $# >= 1 )); then
col_delim_in="$1"
fi
if (( $# >= 2 )); then
col_delim_out="$2"
fi
awk -F "$col_delim_in" '
BEGIN {}
{
for (i=1; i<=NF; i++) {
if (i!=1) {
printf("'"${col_delim_out}"'");
}
printf("%s", $i);
}
printf("\n");
} END {}'
}
get_cols() {
local col_idx_arr=()
local col_delim_in=''
local col_delim_out=''
local col_delim_in_provided=false
local col_delim_out_provided=false
while (( $# != 0 )); do
if [ "$(string_is_posint "$1")" = true ]; then
col_idx_arr+=( "$1" )
elif [ "$col_delim_in_provided" = false ]; then
col_delim_in="$1"
col_delim_in_provided=true
elif [ "$col_delim_out_provided" = false ]; then
col_delim_out="$1"
col_delim_out_provided=true
fi
shift
done
if [ "$col_delim_in_provided" = false ]; then
col_delim_in=' '
fi
if [ "$col_delim_out_provided" = false ]; then
if [ "$col_delim_in_provided" = true ]; then
col_delim_out="$col_delim_in"]
else
col_delim_out=','
fi
fi
awk -F "$col_delim_in" '
BEGIN {}
{
n=split("'"${col_idx_arr[*]}"'", col_idx_arr, " ");
if (n==0) {
for (i=1; i<=NF; i++) {
if (i!=1) {
printf("'"${col_delim_out}"'");
}
printf("%s", $i);
}
printf("\n");
} else {
for (i=1; i<=n; i++) {
if (i!=1) {
printf("'"${col_delim_out}"'");
}
col_idx=col_idx_arr[i];
printf("%s", $col_idx);
}
printf("\n");
}
} END {}'
}
sum_cols() {
local col_delim=' '
if (( $# >= 1 )); then
col_delim="$1"
fi
awk -F "$col_delim" '
BEGIN {}
{
for (i=1; i<=NF; i++) {
sums[i]+=$i;
maxi=i;
}
} END {
for(i=1; i<=maxi; i++) {
if (i!=1) {
printf("'"${col_delim}"'");
}
printf("%s", sums[i]);
}
printf("\n");
}'
}
sum_all() {
local col_delim=' '
if (( $# >= 1 )); then
col_delim="$1"
fi
awk -F "$col_delim" '
BEGIN {}
{
for (i=1; i<=NF; i++) {
sum+=$i;
}
} END {
printf("%s\n", sum);
}'
}
get_stats() {
# Adapted from https://stackoverflow.com/a/9790056/8896374
local perl_cmd
perl_cmd=''\
'use List::Util qw(max min sum);'\
'@num_list=(); while(<>){ $sqsum+=$_*$_; push(@num_list,$_); };'\
'$nitems=@num_list;'\
'if ($nitems == 0) { $sum=0; $min=0; $max=0; $med=0; $avg=0; $std=0; } else {'\
'$min=min(@num_list)+0; $max=max(@num_list)+0; $sum=sum(@num_list); $avg=$sum/$nitems;'\
'$rng=$max-$min; $int=$rng/($nitems-1);'\
'$sqsumtemp=$sqsum/$nitems-($sum/$nitems)*($sum/$nitems); if ($sqsumtemp <= 0) { $std=overflow; } else { $std=sqrt($sqsumtemp); };'\
'$mid=int $nitems/2; @srtd=sort @num_list; if($nitems%2){ $med=$srtd[$mid]+0; }else{ $med=($srtd[$mid-1]+$srtd[$mid])/2; }; };'\
'print "cnt: ${nitems}\nsum: ${sum}\nmin: ${min}\nmax: ${max}\nmed: ${med}\navg: ${avg}\nstd: ${std}\nrng: ${rng}\nint: ${int}\n";'\
'if ($nitems == 0) { exit(1); } else { exit(0); };'
perl -e "$perl_cmd"
}
get_intervals() {
awk 'BEGIN {prev_val="";} {curr_val=$0; if (prev_val!="") print curr_val-prev_val; prev_val=curr_val;}'
}
filesize_diff_perc() {
local base_dir="$1"; shift
local comp_dir="$1"; shift
local find_args=$(escape_regex_special_chars "$*")
paste -d',' \
<(eval find "$base_dir" -type f "$find_args" -print | sort | xargs du --block-size=1K "$@" | awk '{print $1}') \
<(eval find "$comp_dir" -type f "$find_args" -print | sort | xargs du --block-size=1K "$@" | awk '{print $1}') \
| awk -F',' '{print ($2-$1)/$1}' | get_stats
}
# Find operations
#alias findl='find -mindepth 1 -maxdepth 1'
#alias findls='find -mindepth 1 -maxdepth 1 -ls | sed -r "s|^[0-9]+\s+[0-9]+\s+||"'
#alias findlsh='find -mindepth 1 -maxdepth 1 -type f -exec ls -lh {} + | sed -r "s|^[0-9]+\s+[0-9]+\s+||"'
find_alias() {
local find_func_name="$1"; shift
local opt_args_1 path_args opt_args_2 debug depth_arg_provided stock_depth_args find_cmd_suffix
opt_args_1=()
path_args=()
opt_args_2=()
debug=false
depth_arg_provided=false
stock_depth_args=''
find_cmd_suffix=''
local findup_direct=false
local findup_minheight=''
local findup_maxheight=''
local parsing_opt_args arg arg_opt argval
parsing_opt_args=false
while (( $# > 0 )); do
arg_raw="$1"
argval_raw="$2"
arg=$(printf '%q' "$arg_raw")
argval=$(printf '%q' "$argval_raw")
if [[ $arg == -* ]]; then
parsing_opt_args=true
arg_opt=$(echo "$arg" | sed -r 's|\-+(.*)|\1|')
if [ "$arg_opt" = 'db' ] || [ "$arg_opt" = 'debug' ] || [ "$arg_opt" = 'dr' ] || [ "$arg_opt" = 'dryrun' ]; then
debug=true
shift; continue
elif [ "$find_func_name" = 'findup' ] && [ "$arg_opt" = 'direct' ]; then
findup_direct=true
shift; continue
elif [ "$find_func_name" = 'findup' ] && [ "$arg_opt" = 'minheight' ]; then
findup_minheight="$argval"
shift; shift; continue
elif [ "$find_func_name" = 'findup' ] && [ "$arg_opt" = 'maxheight' ]; then
findup_maxheight="$argval"
shift; shift; continue
elif [ "$arg_opt" = 'mindepth' ] || [ "$arg_opt" = 'maxdepth' ]; then
depth_arg_provided=true
if [ "$find_func_name" = 'findup' ]; then
echo_e "findup: mindepth/maxdepth options are not supported, use minheight/maxheight instead"
return
fi
elif [ "$arg_opt" = 'H' ] || [ "$arg_opt" = 'L' ] || [ "$arg_opt" = 'P' ]; then
opt_args_1+=( "$arg" )
shift; parsing_opt_args=false; continue
elif [ "$arg_opt" = 'D' ] || [ "$arg_opt" = 'Olevel' ]; then
opt_args_1+=( "$arg" "$argval" ); shift
shift; parsing_opt_args=false; continue
fi
elif [[ $arg_raw == [\!\(\)\;] ]]; then
parsing_opt_args=true
fi
if [ "$parsing_opt_args" = true ]; then
opt_args_2+=( "$arg" )
else
path_args+=( "$arg_raw" )
fi
shift
done
if [ "$find_func_name" = 'findup' ]; then
local path_src path_tmp depth_args
if (( ${#path_args[@]} == 0 )); then
path_args+=( '.' )
fi
for path_src in "${path_args[@]}"; do
path_tmp=$(fullpath "$path_src")
depth=0
while true; do
if [ -n "$findup_maxheight" ] && (( depth > findup_maxheight )); then
break
fi
if [ "$findup_direct" = true ] || (( depth == 0 )) || [ "$path_tmp" = '/' ]; then
depth_args="-mindepth 0 -maxdepth 0"
else
depth_args="-mindepth 1 -maxdepth 1"
fi
if [ -z "$findup_minheight" ] || (( depth >= findup_minheight )); then
cmd="find ${opt_args_1[*]} \"${path_tmp}\" ${depth_args} ${opt_args_2[*]} ${find_cmd_suffix}"
if [ "$debug" = true ]; then
echo "$cmd"
else
eval "$cmd"
fi
fi
if [ "$path_tmp" = '/' ]; then
break
fi
path_tmp=$(dirname "$path_tmp")
if [ "$findup_direct" = false ] && (( depth == 0 )); then
path_tmp=$(dirname "$path_tmp")
fi
((depth++))
done
done
else
local stock_depth_funcs=( 'findl' 'findls' 'findlsh' 'findd1' )
if [ "$(itemOneOf "$find_func_name" "${stock_depth_funcs[@]}")" = true ] && [ "$depth_arg_provided" = false ]; then
stock_depth_args="-mindepth 1 -maxdepth 1"
fi
if [ "$find_func_name" = 'findl' ]; then
find_cmd_suffix=''
elif [ "$find_func_name" = 'findls' ]; then
find_cmd_suffix="-ls | sed -r 's|^[0-9]+\s+[0-9]+\s+||'"
elif [ "$find_func_name" = 'findlsh' ]; then
find_cmd_suffix=" -type f -exec ls -lh {} + | sed -r 's|^[0-9]+\s+[0-9]+\s+||'"
elif [ "$find_func_name" = 'findd1' ]; then
find_cmd_suffix=" -type d"
fi
cmd="find ${opt_args_1[*]} ${path_args[*]} ${stock_depth_args} ${opt_args_2[*]} ${find_cmd_suffix}"
if [ "$debug" = true ]; then
echo "$cmd"
else
eval "$cmd"
fi
fi
}
findup() {
find_alias findup "$@"
}
findl() {
find_alias findl "$@"
}
findls() {
find_alias findls "$@"
}
findlsh() {
find_alias findlsh "$@"
}
findst() {
find_alias findls "$@" -mindepth 0 -maxdepth 0
}
findd1() {
find_alias findd1 "$@"
}
find_missing_suffix() {
local search_dir base_suffix check_suffix_arr suffix_exist_cond debug
search_dir="$1"; shift
base_suffix="$1"; shift
check_suffix_arr=()
suffix_exist_cond='all'
inverse=false
debug=false
local arg
while (( $# > 0 )); do
arg="$1"
if ! [[ $arg == -* ]]; then
check_suffix_arr+=( "$arg" )
else
arg_opt=$(echo "$arg" | sed -r 's|\-+(.*)|\1|')
if [ "$arg_opt" = 'db' ] || [ "$arg_opt" = 'debug' ] || [ "$arg_opt" = 'dr' ] || [ "$arg_opt" = 'dryrun' ]; then
debug=true
elif [ "$arg_opt" = 'any' ]; then
suffix_exist_cond='any'
elif [ "$arg_opt" = 'all' ]; then
suffix_exist_cond='all'
elif [ "$arg_opt" = 'inverse' ]; then
inverse=true
else
break
fi
fi
shift
done
if [ "$suffix_exist_cond" = 'all' ]; then
require_all_suffix_exist=true
elif [ "$suffix_exist_cond" = 'any' ]; then
require_all_suffix_exist=false
fi
if [ "$debug" = true ]; then
find_alias find_missing_suffix "$search_dir" "$@" -name "*${base_suffix}" -print0 -debug
elif [ "$require_all_suffix_exist" = true ]; then
while IFS= read -r -d '' base_dirent; do
base_dirent_nosuff="${base_dirent%"${base_suffix}"}"
all_exist=true
for suffix in "${check_suffix_arr[@]}"; do
check_dirent="${base_dirent_nosuff}${suffix}"
if [ ! -e "$check_dirent" ]; then
all_exist=false
break
fi
done
if { [ "$all_exist" = false ] && [ "$inverse" = false ]; }\
|| { [ "$all_exist" = true ] && [ "$inverse" = true ]; }; then
echo "$base_dirent"
fi
done < <(find_alias find_missing_suffix "$search_dir" "$@" -name "*${base_suffix}" -print0)
elif [ "$require_all_suffix_exist" = false ]; then
while IFS= read -r -d '' base_dirent; do
base_dirent_nosuff="${base_dirent%"${base_suffix}"}"
some_exist=false
for suffix in "${check_suffix_arr[@]}"; do
check_dirent="${base_dirent_nosuff}${suffix}"
if [ -e "$check_dirent" ]; then
some_exist=true
break
fi
done
if { [ "$some_exist" = false ] && [ "$inverse" = false ]; }\
|| { [ "$some_exist" = true ] && [ "$inverse" = true ]; }; then
echo "$base_dirent"
fi
done < <(find_alias find_missing_suffix "$search_dir" "$@" -name "*${base_suffix}" -print0)
fi
}
ls_suffix() {
ls -1 ${1}* | sed "s|^${1}||"
}
## Package management
apt_cleanup() {
sudo apt-get update && sudo apt-get autoclean && sudo apt-get clean && sudo apt-get autoremove
}
conda_history() {
conda env export --from-history
}
pip_history() {
python -m pip list --verbose
}
## Git
git_remote() {
git config --get remote.origin.url
}
git_webpage() {
if ! git rev-parse --is-inside-work-tree 1>/dev/null; then
return
fi
local get_url_cmd="git config --get remote.origin.url"
local url=$(eval "$get_url_cmd")
if [ -z "$url" ]; then
echo "Repo lookup command returned nothing: '${get_url_cmd}'"
return
fi
url="${url##*@}"
url="${url//://}"
if ! echo "$url" | grep -q '^http'; then
url="https://${url}"
fi
open -a "Google Chrome" "$url"
}
git_drop_all_changes() {
git checkout -- .