Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to file, but overwrite it if it exists

Tags:

bash

unix

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 already exists. Right now this script just appends.

like image 994
switz Avatar asked Jan 13 '11 03:01

switz


People also ask

How do I overwrite an existing file?

Overwriting a File, Part 1 To edit the settings for a file, locate the file you wish to overwrite and hover over the file name. Click the chevron button that appears to the right of the file name and select Overwrite File from the menu.

What mode overwrite existing text in a file?

Example 1: Using the open() method to overwrite a file. To overwrite a file, to write new content into a file, we have to open our file in “w” mode, which is the write mode. It will delete the existing content from a file first; then, we can write new content and save it. We have a new file with the name “myFile. txt”.

Does write overwrite file Python?

Python file write() function Due to a flag, it will append the content after the existing content. It does not overwrite the content.


2 Answers

The >> redirection operator will append lines to the end of the specified file, where-as the single greater than > will empty and overwrite the file.

echo "text" > 'Users/Name/Desktop/TheAccount.txt' 
like image 80
Nylon Smile Avatar answered Sep 22 '22 01:09

Nylon Smile


In Bash, if you have set noclobber a la set -o noclobber, then you use the syntax >|

For example:

echo "some text" >| existing_file 

This also works if the file doesn't exist yet


  • Check if noclobber is set with: set -o | grep noclobber

  • For a more detailed explanation on this special type of operator, see this post

  • For a more exhaustive list of redirection operators, refer to this post

like image 39
BrDaHa Avatar answered Sep 24 '22 01:09

BrDaHa