How to prevent sed command overwriting the original file and output a new file?
In the UPPER.txt file, I need to substitute APPLE and ORANGE with non-capital apple and orange. I also need to keep the old file UPPER.txt as it was, and a generate a new file lower.txt. I am using the following commands:
sed 's/APPLE/apple/g' UPPER.txt > lower.txt
sed 's/ORANGE/orange/g' UPPER.txt > lower.txtBut the problem is that after I run the above command UPPER.txt and lower.txt become the same containing non-capital items. I want the UPPER.txt to remain as it was originally.
How can I keep a backup of the original file after using sed?
Since I want to use this command in C++ using system(command) to operate on the files, I would like all the commands to be written in one line then I can pass it as string to system command.
2 Answers
The command you mentioned sed 's/APPLE/apple/g' UPPER.txt > lower.txt shouldn't overwrite the original UPPER.txt, because sed's default behavior is to write to lower.txt. There's something else you've done that may have overwritten the original file. sed doesn't touch the original file unless you provide -i flag. For your purposes, I'd suggest first making a backup of the original file, aka just copy it.
On a side note, please be aware that system() call is kinda evil and shouldn't be used,
I think you have got some misunderstandings.
The sed command only outputs the result in bash. It has nothing to do with original file. The > operator only writes the result to a file.
However, if you want, there is option -i which is able to edit the original file. With -i option comes backup suffix (optional).
$ cat UPPERCASE.txt
APPLE
$ sed 's/APPLE/apple/g' UPPERCASE.txt
apple
$ sed 's/APPLE/apple/g' UPPERCASE.txt > lowercase.txt
$ cat UPPERCASE.txt
APPLE
$ cat lowercase.txt
apple
$ sed 's/APPLE/apple/g' -i[BACKUP] UPPERCASE.txt
$ cat UPPERCASE.txt
apple
$ ls
UPPERCASE.txt UPPERCASE.txt[BACKUP] lowercase.txtHere, the [BACKUP] file is the original file.