34

我正在尝试编写一个脚本,该脚本将使用 echo 并写入/附加到文件中。但是我已经在字符串中有“”的语法..说..

echo "I am "Finding" difficult to write this to file" > file.txt
echo "I can "write" without double quotes" >> file.txt

任何人都可以帮助理解这一点,非常感谢。

BR, SM

4

2 回答 2

47

如果你想有引号,那么你必须使用反斜杠字符来转义它们。

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
于 2013-06-19T10:49:15.333 回答
22

如果您有特殊字符,您可以使用反斜杠对其进行转义,以便根据需要使用它们:

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

于 2013-06-19T10:56:31.093 回答