gpt4 book ai didi

带有特殊字符的 Linux cat 内联文件

转载 作者:太空狗 更新时间:2023-10-29 11:12:13 27 4
gpt4 key购买 nike

我有以下脚本:

#!/bin/bash
cat << EOF
A^@B^AC^B
EOF

地点:

  • '^@' = 十进制值 0
  • '^A' = 十进制值 1
  • '^B' = 十进制值 2

所以,文件看起来像这样:

xxd main.sh
00000000: 2321 2f62 696e 2f62 6173 680a 0a63 6174 #!/bin/bash..cat
00000010: 203c 3c20 454f 460a 4100 4201 4302 0a45 << EOF.A.B.C..E
00000020: 4f46 0a OF.

当我运行脚本时,十进制值 0 和 1 似乎消失了:

./main.sh | xxd
00000000: 4142 4302 0a ABC..

我的问题是为什么?我期待有这样的输出:

字符“A”,后跟十进制值 0,后跟“B”,后跟十进制值 1,后跟“C”,再后跟十进制值 2。

最佳答案

原因似乎有两个。

首先,请注意您必须在 here-document引用单词/delimiter 避免扩展:

If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \newline is ignored, and ‘\’ must be used to quote the characters ‘\’, ‘$’, and ‘`’.

所以,如果你这样写:

#!/bin/bash
cat <<"EOF"
A^@B^AC^B
EOF

您将保留除 NULL (\0) 之外的所有字符。

但是您不能在任一变量或命令行参数中使用 NULL 字符(参见 this answer)。

不过,您可以在管道/文件中使用 NULL,因此您可能希望对 here-document 的内容进行编码并即时对其进行解码(例如使用 xxd ).

关于带有特殊字符的 Linux cat 内联文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47140193/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com