tsvins (1406B)
1 #!/bin/sh 2 # vim: set ft=bash: 3 # tsvins - Insert a line to a TSV file 4 # This program is licensed under the terms of GNU GPL v3 or (at your option) 5 # any later version. Copyright (C) 2023-2026 Страхиња Радић. 6 # See the file LICENSE for exact copyright and license details. 7 8 tab=$(printf "\t") 9 nl=' 10 ' 11 12 usage() 13 { 14 cat <<EOT 15 Usage: ${0##*/} tsvfile.tsv [lineno] 16 EOT 17 } 18 19 error() 20 { 21 printf "%s: %s\n" "${0##*/}" "$@" >&2 22 } 23 24 case $# in 25 1) inputfile=$1 26 lineno='' 27 ;; 28 2) inputfile=$1 29 lineno=$2 30 ;; 31 *) usage 32 exit 1 33 ;; 34 esac 35 36 [ ! -f "${inputfile}" ] && touch -- "${inputfile}" 37 38 if [ -L $inputfile ]; then 39 inputfile=$(readlink -f $inputfile) 40 fi 41 tmpf=${inputfile}~ 42 numlines=$(awk 'END {print NR}' "${inputfile}") 43 # shellcheck disable=SC2086 44 [ ! $lineno ] && lineno=$((numlines+1)) 45 command -v vipe >/dev/null 2>&1 || { error "vipe not found"; exit 1; } 46 47 touch -- "$tmpf" 48 # shellcheck disable=SC2064 49 trap "rm -f -- \"$tmpf\"" HUP PIPE INT QUIT TERM EXIT 50 51 { if [ "${numlines}" -gt 0 ]; then 52 if [ "${lineno}" -gt 0 ]; then 53 head -n"${lineno}" -- "${inputfile}" 54 fi 55 fi 56 # shellcheck disable=SC1003 57 sed '/^#/d;s/\([^'"$tab"']*\)$/\1'"$tab"'/g' | tr -d '\n' | 58 sed 's/'"$tab"'$/\'"$nl"'/g' 59 if [ "${numlines}" -gt 0 ]; then 60 tail +$((lineno + 1)) -- "${inputfile}" 61 fi; } > "$tmpf" 62 63 if diff -- "$tmpf" "${inputfile}" >/dev/null 2>&1; then 64 rm -- "$tmpf" 65 else 66 mv -- "$tmpf" "${inputfile}" 67 fi