How to replace a string in a text file
Hi, I'm using like:
$sed 's/string1/string2/' file1 > out then, the modified result will be put into out but when i used: $sed 's/string1/string2/' file1 > file1 then the file called file1 will become empty! what's wrong? I just want to replace string1 in file1 to be string2!! thanks! |
also, what about replacing 2 or 3 strings in a text file??? do i just add a
"-e" in the command ??? or i need more stuff?? |
Quote:
This is the more traditional way of doing things: Code:
$ cp file1 file1.bak Code:
$ cat file1 | sed 's/string1/string2/' > file1 Code:
$ sed -i 's/string1/string2/' file1 Code:
$ sed -i.bak 's/string1/string2/' file1 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 |
Try this
Quote:
Code:
$sed 's/string1/string2/' file1 1> file1 |
All times are GMT -5. The time now is 08:59 AM. |