Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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= "" 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= "" 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
And please if I had some solution then why would I ask a question. @Jobin – Muhammad Abdullah Apr 1 '14 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 '14 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 '14 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 – c0rp Apr 1 '14 at 7:21
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 '14 at 10:12

Your Answer


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.