【问题标题】:How can I write and append using echo command to a file如何使用 echo 命令写入和附加到文件
【发布时间】: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

【问题讨论】:

    标签: shell scripting


    【解决方案1】:

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

    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
    

    【讨论】:

    • 感谢您的帮助。早些时候我忘了告诉单引号。是的,我尝试了单引号,这对我有用,但没有达到目的。尝试使用转义反斜杠字符.. 谢谢,SM
    • 谢谢各位,使用反斜杠现在已经完成了,也实现了我的目的。你们真是太棒了。问候,SM
    • 它对我不起作用! 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
    【解决方案2】:

    如果你有特殊字符,你可以用反斜杠转义它们以根据需要使用它们:

    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 开关以防止覆盖。
    猜你喜欢
    • 2019-03-22
    • 1970-01-01
    • 2012-02-24
    • 2016-10-27
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多