10 sed command examples in Linux

 



The sed command is a very useful and powerful command in Linux. Since most of us have each own way of learning, we don't pay to much attention to this command. In this article, check out following 10 examples on using sed command. 


What is sed command?


The sed command is a stream editor for filtering and tranformating text. With sed command, you can:


- select text

- substitute text

- add lines to text

- delete lines

modify the file and much more



1. The following command shall list the file stream.txt without options.


# sed '' stream.txt 




2. The following command uses -p flag to print the current pattern space.


# sed 'p' stream.txt 




Pay close attention that the p flag in above example, has doubled the text line in file stream.txt


3. In order to remove a single character on the fly using sed command, we can type the following command.


# sed 's/a//' stream.txt 




In the above example we have:


- s replace swith

- a character to remove 

- // remove single space 


4. In order to make a permanent changes to a file, we can use the following command:


# sed -i  's/a//' stream.txt 




In above sample -i flag is used to make a permanent changes to a file. 


5. In order to replace a character inside a file, we can type the following command.


# sed  's/sample/example/' stream.txt




In the above example, sed command has replaced 'sample' word with 'example'. 


6. In order to make a globally replacement, we can type the following command.


# sed -i  's/sample/example/g'  stream.txt




The -g flag in above example is used to make a globally changes into a file. 


7. In the following example, the 'a' will be replaced with 'the'. Here's the command.


# sed  's/a/the/'  stream.txt




8. Replace the character on a start of the line. Here's the command.


# sed  's/^this/This/'  stream.txt




The ^ sign tells the sad command in above example, to replace 'this' with 'This' on the beginning of the line.


9. Replace the character at the end of a line. Here's the command.




In the above example, sed command uses the dollar $ sign, to replace the 'file' word at the end of a file into '1'. 


10. List specific number of lines in a file. Here's the command.


# sed   -n   '1,6p'  stream.txt




As we can see in above example, the command has listed using -n flag, range of lines from 1 to 6. 



Conclusion


This was 10 useful examples on using the sed command. For further reading, use the man page of sed command as well as other online resources that are detailing the work with this powerful command in more detail with more examples. Till the next time. 

Share:

Nema komentara:

Objavi komentar

POPULARNI POSTOVI

NAJNOVIJE