bash手册上写着关于命令替换
Bash通过执行命令并将命令替换为命令的标准输出来执行扩展,并删除所有尾随的换行符。
演示-3个字符,换行符第一:
$ output="$(printf "\n\nx")"; echo -n "$output" | wc -c
3在这里,换行符不在末尾,也不被移除,所以计数是3。
演示-3个字符,换行符最后:
$ output="$(printf "x\n\n")"; echo -n "$output" | wc -c
1这里,从末尾移除换行符,所以计数是1。
TL;DR
什么是健壮的工作来将命令的二进制干净输出输入到变量中?
伯恩外壳兼容性加分。
发布于 2016-10-05 05:55:32
以"Bourne兼容“的方式进行此操作的唯一方法是使用外部实用程序。
除了在c ++中写一个,您还可以使用xxd和expr (例如):
$ output="$(printf "x\n\n"; printf "X")" # get the output ending in "X".
$ printf '%s' "${output}" | xxd -p # transform the string to hex.
780a0a58
$ hexstr="$(printf '%s' "${output}" | xxd -p)" # capture the hex
$ expr "$hexstr" : '\(.*\)..' # remove the last two hex ("X").
780a0a
$ hexstr="$(expr "$hexstr" : '\(.*\)..') # capture the shorter str.
$ printf "$hexstr" | xxd -p -r | wc -c # convert back to binary.
3缩短:
$ output="$(printf "x\n\n"; printf "X")"
$ hexstr="$(printf '%s' "${output}" | xxd -p )"
$ expr "$hexstr" : '\(.*\)..' | xxd -p -r | wc -c
3命令xxd用于将其转换为二进制文件的能力。
请注意,对于许多UNICODE字符(多字节字符),wc将失败:
$ printf "Voilà" | wc -c
6
$ printf "★" | wc -c
3它将打印字节数,而不是字符。
变量${#var}的长度在旧的shell中也会失败。
当然,要使它在Bourne中运行,必须使用`…`而不是$(…)。
发布于 2016-10-05 03:12:25
在bash中,可以使用${parameter%word}形式的壳参数展开:
$ output="$(printf“x\n\n;echo X)";echo -n "${output%X}”{output%X}“\ wc -c 3
这也是由POSIX.1-2008指定的替换。
https://stackoverflow.com/questions/39864848
复制相似问题