Pages

Wednesday, December 12, 2012

find and replace linux command line

find and replace linux command line

We have a command line Find and replace utility in linux called "sed"
"sed" stands for Stream Editor.

Consider I have the following file.

<a href="HelloWorld1.pdf">
<a href="HelloWorld2.pdf">
<a href="HelloWorld3.pdf">
<a href="HelloWorld4.pdf">

the above contents are saved in the file test.txt

Now I want to have  the file names only(with in quotes)
(i.e)

HelloWorld1.pdf
HelloWorld2.pdf
HelloWorld3.pdf
HelloWorld4.pdf


The following piece of script will do that.

cat test.txt | sed "s/<a\shref=\"//" | sed "s/\">//"

When we observe the sed command, we will have 's' in the beginning.

@ First sed 


SymbolMeaning
s/Indicates String to be searched
\sSpace
\"Ignore Special Meaning and treat a Quotations
//Replace with nothing



At this time, the output will be as follows.

HelloWorld1.pdf">

HelloWorld2.pdf">

HelloWorld3.pdf">

HelloWorld4.pdf">
 

Now we need to replace the quotes and > at the end of each line.
So we write a second sed.

@ Second sed


SymbolMeaning
s/Indicates String to be searched
\"Ignore Special Meaning and treat a Quotations
>Find the > symbol
//Replace with nothing




No comments:

Post a Comment