DEV Community

HasOne
HasOne

Posted on • Edited on

3 3

Working with sed command in Linux

When working with files in Unix-like systems, sed will help you a lot in updating some text in the existing line, deleting, and even inserting, isn't it cool?

Basic

just open up your terminal and type sed --help, you'll get the usage of sed.

Print file:

Now let's print the file ( like cat ):
sed 'p' /etc/passwd

p operator in single quote will print the file. it's basically working like cat command, but if you've noticed there is a problem we're getting line twice, how to get it rid

sed -n 'p' /etc/passwd

-n flag will only give us the updated file.

Let's suppose if we need to print from lines 1 to 3, so how would we do that?
sed -n '1,3 p' /etc/passwd

in the single quotes, the number refers to line from 1 to 3. we just rebuild the head command using sed. isn't it cool!

Advance

let's find some specific text in a file, I'm gonna find my user name in the file:
sed -n '/^pi/ p' /etc/passwd

/^ caret character means the beginning of line find 'pi' text
p for printing

Now let's update the some text, I wanna update the '/bash' to '/sh':
sed -n '/^pi/ s/bash/sh/ p' /etc/passwd

s for substitute (updating) '/bash' to /sh/'

Let's delete the line by using line number:
sed 'Nd' <filename>

N for specifying line number
d for deleting

Best example

sed -i.bak '/^\s*#/d;/^$/d' <file>

this command will help you to remove white space, comment and will give you a new file. and the original will be saved in .bak extension.

Thanks!

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more