18.01.2020 Views

Working with Linux

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Sed – one-liner productivity treasure

If a picture is worth 1000 words, then sed one liners are definitely worth a thousand lines of code!

One of the most feared commands in the Linux CLI is, you guessed it, sed! It's been feared by

programmers and sysadmins everywhere, because of it's cryptic usage, but it can serve as a very

powerful tool for quickly editing large amounts of data.

We have created five files to help demonstrate the power of this awesome tool. The first one is a

simple file containing the humble line of text: Orange is the new black. Let's start by creating a

simple sed command to replace the word black with white.

The first argument of sed is the replace command. It's divided into 3 parts by 3 /. The first part is s

for substitute, the second part is the word to be replaced, black, in our case, and the third part is the

replacement word, white.

The second argument is the input, in our case, a file:

sed "s/black/white/" 1.txt

Now, the result will be printed on the screen, and you can see the word black has been replaced by

white.

Our second example contains yet another line of text, this time with the word black in both upper and

lower case. If we run the same command using this new file, we will see that it replaces only the

word that matches the case. If we want to do a case insensitive replace, we will add two more

characters to the end of our sed command; g and l.

g: It means global replace, used for replacing all the occurrences in the file. Without this, it will

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!