Quote:
Originally posted by jpan
$sed 's/string1/string2/' file1 > file1
then the file called file1 will become empty!
|
When you use the output redirector ( > ), it automatically creates an empty file. The system has to prepare for output first, before any commands are executed, meaning the empty output file has to be created before the sed command. Since your output file and your input file are the same file, it gets wiped out before sed runs.
This is the more traditional way of doing things:
Code:
$ cp file1 file1.bak
$ sed 's/string1/string2/' file1.bak > file1
or
Code:
$ cat file1 | sed 's/string1/string2/' > file1
or
Code:
$ sed -i 's/string1/string2/' file1
or
Code:
$ sed -i.bak 's/string1/string2/' file1
The man pages are your friend.
The last one will create a backup of the original file by appending ".bak" to the end of the original filename. In this case, it would create a file1.bak.
As for multiple string replacement, why not just try it? You're not going to break anything. Experimenting is part of how to learn. But to give a direct answer to your question: yes, you can do multiple replacements in one command. Just preface each 's///' with a -e. The replacements will be executed in order. So it is possible for a later replacement to change the results of an earlier one. For instance
Code:
$ sed -i.bak -e 's/an example/two strings replaced/' -e 's/string/command/' file1
The code above would first change 'an example' to 'two strings replaced', and the second expression would then overwrite the 'string' with 'command', giving 'two commands replaced' as its final output. Other occurences of 'string' in the file will be replaced with 'command' as normal.