Text and File Processing Using sed in Linux Commands



Sed is a stream editor. A stream editor is used to participate in normal textual content transformations on an enter a file. At the same time in some approaches much like an editor which allows scripted edits (comparable to ed). sed works by means of making only one cross over on the input(s) and is more efficient. Now, let us explore more about – “Text and File processing using sed Linux Commands”.

Firstly, to verify the sed version, use the following command –

$ sed --v

The sample output should be like this –

sed (GNU sed) 4.2.2
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
.........................................................................................

In the below example, abc.txt is the file name.

Sed Commands along with Description

S.No Command Description
1 $sed ‘s/tutorials/tutorialspoint/’ abc.txt It replaces the word “tutorials” To “tutorialspoint”
2 $sed ‘$d’ abc.txt It deletes the last line in abc.txt file
3 $sed ‘s/^[ ^t]*//’ abc.txt It removes the all spaces in front of every line in abc.txt file
4 $sed ‘s/[ ^t]*$//’ file.txt It deletes the all spaces in end of every line in abc.txt file
5 $sed ‘s/tutorials/tutorialspoint/p’ abc.txt It prints the line twice in abc.txt file which contains given string
6 $ sed ‘s/tutorialspoint/tutorials/g’ abc.txt It is a globle replace command to replace “tutorialspoint” to “tutorials” in abc.txt file
7 $ sed -n ‘s/tutorialspoint/tutorials/p’ abc.txt It shows the replaced lines in abc.txt
8 $sed ‘1 s/tutorialspoint/tutorials/’ abc.txt It replaces string of specified line(in the above command, it replaces first line(1)) in abc.txt file
9 $ sed ‘1,3 s/tutorialspoint/tutorials/’ abc.txt It replaces the string specific range(in the above exaple it replaces the string from first line to third line) in abc.txt file
10 $sed ‘/./,$!d’ abc.txt It removes the all empty lines in abc.txt file
11 $sed ‘3,$ d’ abc.txt It removes particular line(Third line) in abc.txt file
12 $sed ‘p’ abc.txt It prints each line in two times in abc.txt file
13 $ sed ‘i “Add a new line”‘ abc.txt It adds the given line(Add a new line) at front of every line in abc.txt file
14 $ sed ‘a “Add a new line”‘ abc.txt It adds the given line(Add a new line) at end of every line in abc.txt file
15 $sed -n ‘/tutorialspoint/ p’ abc.txt It finds the given search string(tutorialspoint) in every line of abc.txt file

In this article, we have learnt about – Learn Text and File processing using sed Linux Commands. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!

Updated on: 2020-01-17T09:50:36+05:30

575 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements