【发布时间】:2013-06-15 20:51:57
【问题描述】:
我正在尝试编写一个脚本,该脚本将使用 echo 并写入/附加到文件。 但是我在字符串中已经有“”的语法..说..
echo "I am "Finding" difficult to write this to file" > file.txt
echo "I can "write" without double quotes" >> file.txt
谁能帮忙理解一下,非常感谢。
BR, SM
【问题讨论】:
我正在尝试编写一个脚本,该脚本将使用 echo 并写入/附加到文件。 但是我在字符串中已经有“”的语法..说..
echo "I am "Finding" difficult to write this to file" > file.txt
echo "I can "write" without double quotes" >> file.txt
谁能帮忙理解一下,非常感谢。
BR, SM
【问题讨论】:
如果你想有引号,那么你必须使用反斜杠字符来转义它们。
echo "I am \"Finding\" difficult to write this to file" > file.txt echo
echo "I can \"write\" without double quotes" >> file.txt
如果您也想自己编写 \ 也是如此,因为它可能会导致副作用。所以你必须使用\\
另一种选择是使用 `'' 代替引号。
echo 'I am "Finding" difficult to write this to file' > file.txt echo
echo 'I can "write" without double quotes' >> file.txt
但是在这种情况下,变量替换不起作用,所以如果你想使用变量,你必须把它们放在外面。
echo "This is a test to write $PATH in my file" >> file.txt
echo 'This is a test to write '"$PATH"' in my file' >> file.txt
【讨论】:
echo "This is a test to write $PATH in my file" >> file.txt echo 'This is a test to write '"$PATH"' in my file" >> file.txt
如果你有特殊字符,你可以用反斜杠转义它们以根据需要使用它们:
echo "I am \"Finding\" difficult to write this to file" > file.txt
echo "I can \"write\" without double quotes" >> file.txt
不过,你也可以通过 tee 命令使用 shell 的“EOF”功能,这对于编写各种东西来说真的很不错:
tee -a file.txt <<EOF
I am "Finding" difficult to write this to file
I can "write" without double quotes
EOF
这会将您想要的几乎任何内容直接写入该文件,并转义任何特殊字符,直到您到达EOF。
*已编辑添加附加开关,以防止覆盖文件:-a
【讨论】:
-a 开关以防止覆盖。