Use sed to Remove Characters in a File

Published by Torry Crass on

I needed to come up with this and it took me a bit to find the simplest solution so I thought I would share it. Please note that this is a Linux solution.

Problem: You have one line in a multi line file that contains a character (or set of characters) that you want to replace or remove.

Solution: There are plenty of options out there but I've been having good luck with using sed and wanted to use it for this. As it turns out it's fairly simple but if you go searching around for this solution on Google, you're liable to run into all kinds of overly complex solutions. As such, here's the command with variables capitalized:

Syntax Version: sed -i '/STRING-TO-SEARCH-FOR/ s/CHARACTERS-TO-REPLACE/CHARACTERS-TO-REPLACE-WITH/' FILE-TO-EDIT

This should be quite easy to modify to suit. Now, for a specific example. Let's say that you have a file named myfile.txt that contains the following two lines of text:

Quotes of Famous People
"A computer would deserve to be called intelligent if it could deceive a human into believing that it was human." – alan turing

As you can see the authors name is not properly capitalized. The following example should resolve that:

Example Version: sed -i '/called intelligent/ s/alan turing/Alan Turing/' myfile.txt

In this example, I searched for a random section of the line that I wanted to isolate. It doesn't matter which part of the line you search for as long as it is unique to the file. I then fed in the string that I wanted to change, followed by what I wanted it changed to which changed the lower-case name to an upper-case name as desired.


0 Comments

Leave a Reply