Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I want to get sub-string of any string using pattern analysis. Example String:

<string module name="Jai" fathername="S.S. Khan" phone="1234">
    <address complete="startz us" />
    <worker company="Delta star" />
<string module name="Jai" phone="1234">
<string module name="Jai" value="" phone="1234">
    <status now="single />
<string module name="Jai" email= "[email protected]" value="" phone="1234">
    <address complete="startz us" />
    <worker company="Delta star" />

I want the following values (greped by phone):

string module name="Jai" fathername="S.S. Khan"
string module name="Jai"
string module name="Jai" value=""
string module name="Jai" email= "[email protected]" value=""

If I run the following command it returns only those rows which have phone:

cat file.txt | grep phone.

To overcome this I am running:

cat file.txt | grep phone | sed 's/phone=".*"/phone=""/g' | grep -v phone`

It works but I want to do this with exactly pattern analysis.

Can anyone help or guide me how can I do so?

share|improve this question
    
What have you tried to get these values? Please show some research effort before you post. –  i08in Apr 1 at 6:48
    
And please if I had some solution then why would I ask a question. @Jobin –  Muhammad Abdullah Apr 1 at 6:58
    
Have copied your comment to your question, reverted the downvote. Its not about the solution, its about what you have tried to find the solution before you post it. –  i08in Apr 1 at 7:00
    
Thanks but after your comments I am thinking about to use my own logic instead of asking people. –  Muhammad Abdullah Apr 1 at 7:03
    
You can try this, sed -e 's/<.*\/>//g;s/phone=".*"//;s/[<>]//g' file.txt. If I understand you correctly. Also this like question should be asked on stackoverflow.com. –  c0rp Apr 1 at 7:21

1 Answer 1

up vote 2 down vote accepted

I guess that you want to use regular expressions to do your pattern analysis. You can try this perl oneliner:

cat file.txt | perl -ne 'print "$1\n" if /(string module name=.*?)phone.*/'
  • perl -ne will analyze your file.txt line by line
  • then it will print only the content of the pattern between the (...)
share|improve this answer
    
Thanks, That's it what I want :) –  Muhammad Abdullah Apr 2 at 10:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.