我想将以下文本附加到Linux中的文件中:
echo He said "I can't append this" >> file.txt
cat file.txt
He said I can't append this
extension不起作用。如何在附加的字符串中包含两组引号?
答案 0 :(得分:5)
最好使用here-doc来避免疯狂逃脱:
cat<<'EOF' > file.txt
He said "I can't append this"
EOF
答案 1 :(得分:1)
您可以按以下方式连接字符串:
echo He said '"'"I can't append this"'"'
或:
echo 'He said "I can'"'"'t append this"'
但可能最好的选择是使用\
转义字符:
echo 'He said "I can\'t append this"' # note: this is wrong - see comment
编辑:正如@ gniourf_gniourf的评论中所述,以前使用转义字符的解决方案是错误的。正确的版本是
echo "He said \"I can't append this\""
答案 2 :(得分:1)
为避免使用cat
,您可以使用printf
:
printf 'He said "%s"\n' "I can't append this" >> file.txt