blob: e237d9360a5e75c3482c7e2fd16930130407456f (
plain)
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
|
#!/bin/bash
###
# Single pass tabulate.
#
# Turn grid-aligned tables into tab-separated values
# using the first line as a template.
# Pre-existing tabs are preserved,
# which is probably not good.
##
# TODO:
# - Optionally require more than one space for column separation.
shopt -s extglob
spitline(){
declare -i prevtab=0
for tabstop in ${tabstops[@]}
do
# Strip trailing spaces.
field=${line:$prevtab:$((tabstop-prevtab))}
field=${field%%*( )}
printf '%s\t' "$field"
prevtab=$tabstop
done
printf '%s\n' "${line:$prevtab}"
}
##
# First line:
##
# The tab stops are where stretches of empty space end.
IFS=$'\n'
read -r firstline
declare -i skip=1
for ((i=0;i<${#firstline};i++))
do
case ${firstline:$i:1} in
\ )
skip=0
;; *)
[[ $skip -eq 0 ]] && tabstops+=($i)
skip=1
esac
done
#echo >&2 ${tabstops[@]}
line=$firstline
spitline
##
# All other lines:
declare -i prevtab
while read -r line
do spitline
done
|