Text and File processing using sed Linux Commands

LinuxOperating SystemSoftware & Coding

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.NoCommandDescription
1$sed ‘s/tutorials/tutorialspoint/’ abc.txtIt replaces the word “tutorials” To “tutorialspoint”
2$sed ‘$d’ abc.txtIt deletes the last line in abc.txt file
3$sed ‘s/^[ ^t]*//’ abc.txtIt removes the all spaces in front of every line in abc.txt file
4$sed ‘s/[ ^t]*$//’ file.txtIt deletes the all spaces in end of every line in abc.txt file
5$sed ‘s/tutorials/tutorialspoint/p’ abc.txtIt prints the line twice in abc.txt file which contains given string
6$ sed ‘s/tutorialspoint/tutorials/g’ abc.txtIt is a globle replace command to replace “tutorialspoint” to “tutorials” in abc.txt file
7$ sed -n ‘s/tutorialspoint/tutorials/p’ abc.txtIt shows the replaced lines in abc.txt
8$sed ‘1 s/tutorialspoint/tutorials/’ abc.txtIt 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.txtIt 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.txtIt removes the all empty lines in abc.txt file
11$sed ‘3,$ d’ abc.txtIt removes particular line(Third line) in abc.txt file
12$sed ‘p’ abc.txtIt prints each line in two times in abc.txt file
13$ sed ‘i “Add a new line”‘ abc.txtIt 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.txtIt adds the given line(Add a new line) at end of every line in abc.txt file
15$sed -n ‘/tutorialspoint/ p’ abc.txtIt 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!

raja
Published on 17-Jan-2020 09:50:36
Advertisements