shtools/ztr/ztr
2020-10-26 11:25:36 +01:00

107 lines
1.9 KiB
Bash
Executable file

#!/bin/sh
usage()
{
echo "ztr [options] [file]
Replace preconfigured text from input
Options:
-h Display help
-l Load files in data dir
-p Generate partitions
-d Generate disks
-P Print lines
-s Print in sed script format"
}
gen_tr_lines_disk()
{
cd /sys/block
for I in *
do
_t=$(zdtol "$I" | head -n1)
[ -n "$_t" ] && printf "/dev/%s:%s\n" "$I" "$_t"
done
}
gen_tr_lines_part() {
lsblk -lnio NAME,LABEL | awk '{if ($2 != "") {printf "/dev/%s:",$1;{for(i=2;i<=NF-1;i++){printf"%s ",$i}; print $NF;}}}'
}
gen_sed_script() {
awk -F ':' '{printf "s|%s|%s|g;" ,$1,$2 }' | head -c-1
}
if [ -n "$XDG_CONFIG_HOME" ]
then
CONFIG_PATH="$XDG_CONFIG_HOME/ztr"
else
CONFIG_PATH="$HOME/.config/ztr"
fi
DATA_PATH=$CONFIG_PATH/data/
while getopts ":hPsf:pdl" opt;
do
_opt=y
case $opt in
h) usage && exit 0 ;;
P) _opt_P=y ;;
s) _opt_s=y ;;
f) _opt_f=y
_arg_f=$OPTARG
_opt_data=y
;;
d) _opt_d=y
_opt_data=y
;;
p) _opt_p=y
_opt_data=y
;;
l) _opt_l=y
_opt_data=y
;;
\?)
echo "Unknown option: $OPTARG" >&2
usage
exit 1
;;
esac
done
shift $((OPTIND-1))
[ -z "$_opt_data" ] && {
_opt_p=y
_opt_d=y
_opt_l=y
_opt_L=y
}
mkdir -p "$DATA_PATH"
LINES=""
[ -n "$_opt_f" ] && LINES="$(printf "%s\n%s" "$LINES" "$(cat "$_arg_f")" )"
[ -n "$_opt_l" ] && LINES="$(printf "%s\n%s" "$LINES" "$(cat "$DATA_PATH"/* 2>/dev/null)" )"
[ -n "$_opt_p" ] && LINES="$(printf "%s\n%s" "$LINES" "$(gen_tr_lines_part)" )"
[ -n "$_opt_d" ] && LINES="$(printf "%s\n%s" "$LINES" "$(gen_tr_lines_disk)" )"
LINES=$(echo "$LINES" | grep -v '^$')
FILE=/dev/stdin
[ -n "$1" ] && FILE="$1"
if [ -t 0 ] || [ -n "$_opt_P" ] && [ -z "$1" ]
then
if [ -n "$_opt_s" ]
then
echo "$LINES" | gen_sed_script
else
echo "$LINES"
fi
else
sed "$(echo "$LINES" | gen_sed_script)" < "$FILE"
fi