string 如何在单引号字符串中使用变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21192420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use variables in single quoted strings?
提问by Pectus Excavatum
I am just wondering how I can echo a variable inside single quotes (I am using single quotes as the string has quotation marks in it).
我只是想知道如何在单引号内回显变量(我使用单引号,因为字符串中有引号)。
echo 'test text "here_is_some_test_text_$counter" "output"' >> ${FILE}
any help would be greatly appreciated
任何帮助将不胜感激
回答by Ignacio Vazquez-Abrams
Variables are expanded in double quoted strings, but not in single quoted strings:
变量在双引号字符串中展开,但不在单引号字符串中展开:
$ name=World
$ echo "Hello $name"
Hello World
$ echo 'Hello $name'
Hello $name
If you can simply switch quotes, do so.
如果您可以简单地切换引号,请这样做。
If you prefer sticking with single quotes to avoid the additional escaping, you can instead mix and match quotes in the same argument:
如果您更喜欢坚持使用单引号以避免额外的转义,您可以在同一参数中混合和匹配引号:
$ echo 'single quoted. '"Double quoted. "'Single quoted again.'
single quoted. Double quoted. Single quoted again.
$ echo '"$name" has the value '"$name"
"$name" has the value World
Applied to your case:
适用于您的案例:
echo 'test text "here_is_some_test_text_'"$counter"'" "output"' >> "$FILE"
回答by glenn Hymanman
use printf:
使用printf:
printf 'test text "here_is_some_test_text_%s" "output"\n' "$counter" >> ${FILE}
回答by William Pursell
Use a heredoc:
使用 heredoc:
cat << EOF >> ${FILE}
test text "here_is_some_test_text_$counter" "output"
EOF
回答by Paul Back
The most readable, functional way uses curly braces inside double quotes.
最易读、最实用的方式是在双引号内使用花括号。
'test text "here_is_some_test_text_'"${counter}"'" "output"' >> "${FILE}"
回答by Kulimak Joco
You can do it this way:
你可以这样做:
$ counter=1 eval echo `echo 'test text \
"here_is_some_test_text_$counter" "output"' | \
sed -s 's/\"/\\"/g'` > file
cat file
test text "here_is_some_test_text_1" "output"
Explanation: Eval command will process a string as command, so after the correct amount of escaping it will produce the desired result.
说明:eval 命令会将字符串作为命令处理,因此在正确的转义量后,它将产生所需的结果。
It says execute the following string as command:
它说将以下字符串作为命令执行:
'echo test text \"here_is_some_test_text_$counter\" \"output\"'
Command again in one line:
在一行中再次命令:
counter=1 eval echo `echo 'test text "here_is_some_test_text_$counter" "output"' | sed -s 's/\"/\\"/g'` > file
回答by Elior Malul
Output a variable wrapped with single quotes:
输出一个用单引号括起来的变量:
printf "'"'Hello %s'"'" world
回答by R.Sicart
with a subshell:
带有子外壳:
var='hello' echo 'blah_'`echo $var`' blah blah';