gopherinfo.sh (1765B)
1 #!/bin/bash 2 # A simple helper tool to create valid Gophermap info lines from the standard input 3 # Features: 4 # - implemented in pure Bash and doesn't depend on wc (that can have a non-standard implementation) 5 # - aligns the spaces according to the longest line so that the output would look nice in plaintext too 6 # - doesn't do any heuristics but allows you to specify the amount of leading and trailing spaces (0 by default) 7 # - allows visual selector/host placeholder customization (';' by default) 8 # - converts LF-only line endings to CRLF (as required by the RFC) without unix2dos dependency 9 # - only outputs to stdout (but you can redirect it into a file if you need to) 10 # 11 # Usage: cat [file] | gopherinfo.sh [leading_spaces] [trailing_spaces] [placeholder_char] 12 # 13 # Created by Luxferre in 2023, released into public domain 14 15 LSPACES="$1" 16 TSPACES="$2" 17 DELIM="$3" 18 19 TAB=$'\t' 20 CRLF=$'\r\n' 21 22 [[ -z "$LSPACES" ]] && LSPACES=0 23 [[ -z "$TSPACES" ]] && TSPACES=0 24 [[ -z "$DELIM" ]] && DELIM=';' 25 26 readarray -t LINES -d $'\n' # read the input line array (split by LF) 27 LINECOUNT=${#LINES[@]} # get the array length 28 MAXLEN=0 # initialize the maximum length variable 29 for ((idx=0;idx<LINECOUNT;idx++)); do # first pass to filter out inconsistent newlines and to detect maximum length 30 line="${LINES[$idx]%%$'\r'}" # remove a trailing CR if it is there 31 llen=${#line} # get the line length 32 (( llen > MAXLEN )) && MAXLEN=$llen # update the current maximum length 33 LINES[$idx]="$line" # update the element by index 34 done 35 fmtstr="%-$(( LSPACES + 1 ))s%-$(( MAXLEN + TSPACES ))s${TAB}%s${TAB}%s${TAB}0${CRLF}" # params: i, line, DELIM, DELIM 36 for line in "${LINES[@]}"; do # second pass to actually output the formatted lines 37 printf "$fmtstr" 'i' "$line" "$DELIM" "$DELIM" 38 done