如何将文件内容用作变量,但保持“ \ 0”

时间:2019-04-24 02:07:40

标签: bash

我有一个用“ \ 0”分隔的文件内容,例如:find ./ -type f -print0 > myfile.txt 然后,我想将文件内容读入变量,但仍保留“ \ 0”。 "$(< myfile.txt)"在这种情况下不起作用,所有的“ \ 0”都带有条纹。

1 个答案:

答案 0 :(得分:7)

定向打击

使用数组,而不是常规(NUL分隔)字符串。

支持bash 3.x(和4.0-4.3):

files=( )
while IFS= read -r -d '' file; do
  files+=( "$file" )
done < <(find . -type f -print0)

...或4.4或更高版本:

readarray -d '' files < <(find . -type f -print0)

无论哪种方式,您都可以使用以下方法重新生成原始流:

printf '%s\0' "${files[@]}"

定位POSIX sh(+ coreutils)

相反,如果您需要支持不支持数组的非bash外壳,则最终需要使用base64编码,uuencoding或另一种对内容进行编码的公式,以使文字NUL不再发生。

因此,假设使用GNU coreutils base64

files_b64=$(find . -type f -print0 | base64 -w 0 -)

...然后,将其解码为原始流:

printf '%s\n' "$files_b64" | base64 -d -

如果coreutils的可移植性不足,则openssl命令行工具可提供类似的功能;进行调整以留给读者练习。