Hello,
I am new to sed and am trying to extract a word using sed.
for example i have a line "const TotalAmount& getTotalAmount() const; " in the file test.txt
I am trying to extract getTotalAmount() from the line.
For this i tried
cat test.txt | sed -n 's/.*get[a-zA-Z]*\(\)//p
But the output is
() const;
Could you please let me know the correct expression or what i am doing wrong.
Also could you please suggest some good basic tutorials for Sed.
For extracting the getTotalAmount() from the string.You use the following command.
sed -r 's/.*(get[a-zA-Z]+\(\)).*/\1/g' <file>
This is the best tutorial for reading about SED.
SED and Regular Expressions
You try this.
echo "const TotalAmount& getTotalAmount() const;" | sed -r 's/.{19}//;s/.{7}$//'
sed -r "s/.*(getTotalAmount\(\)).*/\1/g" file
Try this
cat test | sed -nr 's/.*(get[a-zA-Z]*\(\)).*/\1/p'
Output
getTotalAmount()
I believe that this tutorial would be nice for beginners
Sed - An Introduction and Tutorial
Or you can try this also
sed -re 's/.{19}//;s/.{8}$//' test.txt
Here what I am doing is I am removing the first 19 characters and last 8 characters.
So you can easily get the middle remaining string as "getTotalAmount()".
sed -n "s/.*\(get[a-zA-Z]*()\).*/\1/p" infile
grep -o "get[a-zA-Z]*()" infile
Using following way also you can get the getTotalAmount() from test.txt.
cat test.txt | cut -d ' ' -f 3
Thanks for the replies guys
The solution proposed by abubacker fits a lot my requirements
cat test | sed -nr 's/.*(get[a-zA-Z]*\(\)).*/\1/p'
Actually in the test.txt file I have more than one gets
for eg
asdasda getAmount() asdasda
adsadaa getTax() adasd
etc
Hence this expression matches exactly
Thanks a lot for the solutions.
---------- Post updated at 02:36 AM ---------- Previous update was at 02:32 AM ----------
I was looking to find a solution with grep, and this is a best option... -o
I just changed a bit to fit my requirements. I just added a get at the beginning.
grep -o "get[a-zA-Z]*()" test.txt