3

I have an xml file and i want to extract just the numerical value from a string in the file.One of the solution i came up with is

cat file.xml |grep -i "mu "| grep -o '[0-9]' 

But i get each digit separated by new line,e.g for 100,i get 1 then new line,then 0 and so on.The other solution i came up with is

cat file.xml |grep -i "mu "|cut -d ' ' -f 4| tr '=' ' '|cut -d ' ' -f2|tr '""' ' '|sed -e 's/^ *//g' -e 's/ *$//g' 

My question: Is there a simpler solution to this problem that i get just a numerical value from a line without caring about fields and not to use cut or tr commands?

2
  • Please provide an example of your string Commented Nov 22, 2013 at 17:05
  • <mu value="100" /> But it can be different e.g there can be space between value and = sign. Commented Nov 22, 2013 at 17:08

3 Answers 3

4

Use this egrep:

egrep -o '[0-9]+' 
Sign up to request clarification or add additional context in comments.

1 Comment

Or in context grep -i "mu" file.xml | grep -Eo '[0-9]+'
0

One option you have is to delete everything that is not a digit from your input

tr -cd '[:digit:]' 

Or for floating numbers

tr -cd '[:digit:].' 

1 Comment

Thank you,it worked for me but not very comfortable with [:digit:]
0

I would encourage avoidance of XML as a format, personally; at least for your own use. Instead of "<mu value="100" />", you could use the following:-

# Name your data file ma-me-mo-mu.txt 100+200+300+400 

and then:-

while IFS='+' read ma me mo mu do echo "${ma}" echo "${me}" echo "${mo}" echo "${mu}" done 

You don't need to name your columns inside the data file itself. They go in the file name.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.