Working with sed command in Linux

hasone profile image HasOne ・2 min read

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?


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!


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.


Posted on by:

hasone profile



A tech enthusiast


markdown guide