简单的一行技巧转储数组
我用空格添加了一个值:
foo=([12]="bar" [42]="foo bar baz" [35]="baz")
用于快速转储bash数组或我使用的关联数组
这一行命令:
paste <(printf "%s\n" "${!foo[@]}") <(printf "%s\n" "${foo[@]}")
将呈现:
12 bar
35 baz
42 foo bar baz
解释
Printf "%s\n" "${! "foo[@]}"将打印所有以换行符分隔的键,
Printf "%s\n" "${foo[@]}"将打印所有以换行符分隔的值,
Paste <(cmd1) <(cmd2)将逐行合并cmd1和cmd2的输出。
校准
这可以通过-d switch来调整:
paste -d : <(printf "%s\n" "${!foo[@]}") <(printf "%s\n" "${foo[@]}")
12:bar
35:baz
42:foo bar baz
甚至:
paste -d = <(printf "foo[%s]\n" "${!foo[@]}") <(printf "'%s'\n" "${foo[@]}")
foo[12]='bar'
foo[35]='baz'
foo[42]='foo bar baz'
关联数组的工作原理是一样的:
declare -A bar=([foo]=snoopy [bar]=nice [baz]=cool [foo bar]='Hello world!')
paste -d = <(printf "bar[%s]\n" "${!bar[@]}") <(printf '"%s"\n' "${bar[@]}")
bar[foo bar]="Hello world!"
bar[foo]="snoopy"
bar[bar]="nice"
bar[baz]="cool"
使用换行符或特殊字符
不幸的是,至少有一个条件使这个不再工作:当变量包含换行符:
foo[17]=$'There is one\nnewline'
命令粘贴将逐行合并,因此输出将是错误的:
paste -d = <(printf "foo[%s]\n" "${!foo[@]}") <(printf "'%s'\n" "${foo[@]}")
foo[12]='bar'
foo[17]='There is one
foo[35]=newline'
foo[42]='baz'
='foo bar baz'
对于这项工作,您可以在第二个printf命令中使用%q而不是%s(并使用whpe引号):
paste -d = <(printf "foo[%s]\n" "${!foo[@]}") <(printf "%q\n" "${foo[@]}")
将呈现完美(并且可重用!):
foo[12]=bar
foo[17]=$'There is one\nnewline'
foo[35]=baz
foo[42]=foo\ bar\ baz
来自man bash:
%q导致printf输出a中相应的参数
可以作为shell输入重用的格式。
或者使用函数:
dumpArray() {
local -n _ary=$1
local _idx
local -i _idlen=0
for _idx in "${!_ary[@]}"; do
_idlen=" ${#_idx} >_idlen ? ${#_idx} : _idlen "
done
for _idx in "${!_ary[@]}"; do
printf "%-*s: %s\n" "$_idlen" "$_idx" \
"${_ary["$_idx"]//$'\n'/$'\n\e['${_idlen}C: }"
done
}
然后现在:
dumpArray foo
12: bar
17: There is one
: newline
35: baz
42: foo bar baz
dumpArray bar
foo : snoopy
bar : nice
baz : cool
foo bar: Hello world!
关于UTF-8格式输出
从UTF-8字符串长度,添加:
strU8DiffLen() { local chLen=${#1} LANG=C LC_ALL=C;return $((${#1}-chLen));}
Then
dumpArray() {
local -n _ary=$1
local _idx
local -i _idlen=0
for _idx in "${!_ary[@]}"; do
_idlen=" ${#_idx} >_idlen ? ${#_idx} : _idlen "
done
for _idx in "${!_ary[@]}"; do
strU8DiffLen "$_idx"
printf "%-*s: %s\n" $(($?+$_idlen)) "$_idx" \
"${_ary["$_idx"]//$'\n'/$'\n\e['${_idlen}C: }"
done
}
演示:
foo=([12]="bar" [42]="foo bar baz" [35]="baz")
declare -A bar=([foo]=snoopy [bar]=nice [baz]=cool [foo bar]='Hello world!')
foo[17]=$'There is one\nnewline'
LANG=fr.UTF-8 printf -v bar[déjà] $'%(%a %d %b\n%Y\n%T)T' -1
dumpArray bar
déjà : ven 24 déc
: 2021
: 08:36:05
foo : snoopy
bar : nice
baz : cool
foo bar: Hello world!
dumpArray foo
12: bar
17: There is one
: newline
35: baz
42: foo bar baz