如何在bash here-document中键入选项卡?

D W*_*D W 24 bash tabs heredoc

here-document的定义如下:http: //en.wikipedia.org/wiki/Here_document

如何在here-document中键入选项卡?比如这样:

cat > prices.txt << EOF
coffee\t$1.50
tea\t$1.50
burger\t$5.00
EOF
Run Code Online (Sandbox Code Playgroud)

更新:

这个问题涉及的问题:

  1. 展开制表
  2. 虽然没有扩大美元符号
  3. 将here-doc 嵌入诸如脚本之类的文件中

小智 19

TAB="$(printf '\t')"

cat > prices.txt << EOF
coffee${TAB}\$1.50
tea${TAB}\$1.50
burger${TAB}\$5.00
EOF
Run Code Online (Sandbox Code Playgroud)

  • 特定于bash的快捷方式是`TAB = $'\ t'`,滥用gettext功能. (5认同)

Pau*_*ce. 15

您可以在脚本中嵌入此文档,并将其分配给变量,而不使用单独的文件:

#!/bin/bash
read -r -d '' var<<"EOF"
coffee\t$1.50
tea\t$1.50
burger\t$5.00
EOF
Run Code Online (Sandbox Code Playgroud)

然后printfecho -e\t字符展开到标签中.您可以将其输出到文件:

printf "%s\n" "$var" > prices.txt
Run Code Online (Sandbox Code Playgroud)

或者使用以下方法将变量的值赋给自身printf -v:

printf -v var "%s\n" "$var"
Run Code Online (Sandbox Code Playgroud)

现在var或文件prices.txt包含实际选项卡而不是\t.

您可以在读取此文档时将其处理,而不是将其存储在变量中或将其写入文件中:

while read -r item price
do
    printf "The price of %s is %s.\n" $item $price    # as a sentence
    printf "%s\t%s\n" $item $price                  # as a tab-delimited line
done <<- "EOF"
    coffee $1.50    # I'm using spaces between fields in this case
    tea $1.50
    burger $5.00
    EOF
Run Code Online (Sandbox Code Playgroud)

请注意,<<-在这种情况下,我用于此处的doc运算符.这允许我缩进这里doc的行以便于阅读.缩进必须仅包含制表符(无空格).

  • 在 bash v4.4.19 中,printf 必须使用 %b 格式说明符而不是 %s 来扩展转义制表符 (\t)。请参阅 https://unix.stackexchange.com/a/454069/29426。 (2认同)

mar*_*ton 8

对我来说,我键入ctrl-V,然后按ctrl-I在bash shell中插入一个选项卡.这绕过了拦截制表符的shell,否则它具有"特殊"含义.Ctrl-V后跟一个选项卡也应该有效.

当在这里的文档中嵌入美元符号时,你需要禁用shell变量的插值,或者在每个变量前面添加一个反斜杠来逃避(即\$).

使用您的示例文本,我在price.txt中得到了这个内容:

coffee\t.50
tea\t.50
burger\t.00
Run Code Online (Sandbox Code Playgroud)

因为$1$5没有设定.可以通过引用终结符来关闭插值,例如:

cat > prices.txt <<"EOF"
Run Code Online (Sandbox Code Playgroud)


par*_*par 5

As others have said, you can type CTRL-V then tab to insert a single tab when typing.

You can also disable bash tab-completion temporarily, for example if you want to paste text or if you want to type a long here-doc with lots of tabs:

bind '\C-i:self-insert'     # disable tab-completion

# paste some text or type your here-doc
# note you don't use "\t" you just press tab

bind '\C-i:complete'        # reenable tab-completion
Run Code Online (Sandbox Code Playgroud)

EDIT: If you're on a Mac and use iTerm 2, there is now a "Paste with literal tabs" option that allows pasting code with tabs onto the bash command line.