Suppose you want to replace a text string into a text file. You’re writing your novel in a TXT file and you suddenly want to change the name of the main character. Yes, I know, in 2018 nobody writes a novel using a TXT file. Writers use LibreOffice Writer.
Anyway, it’s just an example.
Suppose you have the file named “myfile.txt” and you want to replace all the “Rose” occurences with “Margaret”.
You need simply to run into bash interpreter:
sed -i 's/Rose/Margaret/g' /path/to/myfile.txt
But what if you want to keep the old file? Use this one:
sed 's/Rose/Margaret/g' /path/to/myfile.txt > /path/to/mynewfile.txt
Ok, but things get more complicated, you decided to change all the names into your story (more sed patterns). You want to do the following renaming:
- Rose -> Margaret
- Steve -> Ben
- Mark -> Oliver
How can you do? Use this sed command (write it in just one line):
sed -i 's/Rose/Margaret/g; s/Steve/Ben/g; s/Mark/Oliver/g' /path/to/myfile.txt
Ok. But suppose your novel has a lots of characters.
You want to replace lots of patterns.
Well, you need to create a file to execute a sed interpreter. Open a text editor (nano, vi, vim, …) and write in it:
#!/usr/bin/sed -f s/Rose/Margaret/g s/Ann/Lola/g s/Carl/John/g s/Steve/Ben/g s/Mark/Oliver/g
Save the file with the name “mysedscript” and than execute in this way:
chmod +x mysedscript ./mysedscript /path/to/myfile.txt > /path/to/mynewfile.txt
That’s it! In
/path/to/mynewfile.txt you will get the same file with the wanted replacement.
Well, if you want an example file to give as input to the sed script try, for example, into the bash console, these commands:
echo "Rose said she's happy" > /path/to/myfile.txt echo "Ann got sick" >> /path/to/myfile.txt echo "Carl wanted to go to the cinema" >> /path/to/myfile.txt echo "Steve's bored" >> /path/to/myfile.txt echo "Mark is alone" >> /path/to/myfile.txt
After the sed script we will get (into
Margaret said she's happy Lola got sick John wanted to go to the cinema Ben's bored Oliver is alone
Any way, to replace special characters as could be “/” you need to replace with “\/” because “/” it’s part of the sed “command”.
sed 's/\///g' /path/to/myfile.txt > /path/to/mynewfile.txt
With this command you will remove all the “/” from the content file
/path/to/myfile.txt, of course you will get this output into the new file
/path/to/myfile.txt. Try to use “-i” option as said at the beginning of this post if you don’t want to keep a backup of the original file.
Any more question?