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)
更新:
这个问题涉及的问题:
小智 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)
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)
然后printf或echo -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的行以便于阅读.缩进必须仅包含制表符(无空格).
对我来说,我键入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)
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.
| 归档时间: |
|
| 查看次数: |
15640 次 |
| 最近记录: |