Write to file, but overwrite it if it exists

前端 未结 8 1548
一个人的身影
一个人的身影 2020-12-07 07:29
echo \"text\" >> \'Users/Name/Desktop/TheAccount.txt\'

How do I make it so it creates the file if it doesn\'t exist, but overwrites it if it

相关标签:
8条回答
  • 2020-12-07 08:07

    Just noting that if you wish to redirect both stderr and stdout to a file while you have noclobber set (i.e. set -o noclobber), you can use the code:

        cmd >|file.txt 2>&1
    

    More information about this can be seen at https://stackoverflow.com/a/876242.

    Also this answer's @TuBui's question on the answer @BrDaHa provided above at Aug 9 '18 at 9:34.

    0 讨论(0)
  • 2020-12-07 08:09

    If you have output that can have errors, you may want to use an ampersand and a greater than, as follows:

    my_task &> 'Users/Name/Desktop/task_output.log' this will redirect both stderr and stdout to the log file (instead of stdout only).

    0 讨论(0)
  • 2020-12-07 08:16

    If your environment doesn't allow overwriting with >, use pipe | and tee instead as follows:

    echo "text" | tee 'Users/Name/Desktop/TheAccount.txt'
    

    Note this will also print to the stdout. In case this is unwanted, you can redirect the output to /dev/null as follows:

    echo "text" | tee 'Users/Name/Desktop/TheAccount.txt' > /dev/null
    
    0 讨论(0)
  • 2020-12-07 08:20
    #!/bin/bash
    
    cat <<EOF > SampleFile
    
    Put Some text here 
    Put some text here
    Put some text here
    
    EOF
    
    0 讨论(0)
  • 2020-12-07 08:26

    Despite NylonSmile's answer, which is "sort of" correct.. I was unable to overwrite files, in this manner..

    echo "i know about Pipes, girlfriend" > thatAnswer

    zsh: file exists: thatAnswer

    to solve my issues.. I had to use... >!, á la..

    [[ $FORCE_IT == 'YES' ]] && echo "$@" >! "$X" || echo "$@" > "$X"
    

    Obviously, be careful with this...

    0 讨论(0)
  • 2020-12-07 08:26

    To overwrite one file's content to another file. use cat eg.

    echo  "this is foo" > foobar.txt
    cat foobar.txt
    
    echo "this is bar" > bar.txt
    cat bar.txt
    

    Now to overwrite foobar we can use a cat command as below

    cat bar.txt >> foobar.txt
    cat foobar.txt
    

    0 讨论(0)
提交回复
热议问题