1

I want to extract a certain part of a string, if it exists. I'm interested in the xml filename, i.e i want whats between an "_" and ".xml".

This is ok, it prints "555"

MYSTRING=`echo "/sdd/ee/publ/xmlfile_555.xml" | sed 's/^.*_\([0-9]*\).xml/\1/'`
echo "STRING = $MYSTRING"

This is not ok because it returns the whole string. In this case I don't want any result. It prints "/sdd/ee/publ/xmlfile.xml"

MYSTRING=`echo "/sdd/ee/publ/xmlfile.xml" | sed 's/^.*_\([0-9]*\).xml/\1/'`
echo "STRING = $MYSTRING"

Any ideas how to get an "empty" result in the second case.

thanks!

3 Answers 3

2

You just need to tell sed to keep its mouth shut if it doesn't find a match. The -n option is used for that.

MYSTRING=`echo "/sdd/ee/publ/xmlfile_555.xml" | sed -n 's/^.*_\([0-9]*\)\.xml/\1/p'`

I only made two changes to what you had: the aforementioned -n option to sed, and the p flag that comes after the s/// command, which tells sed to print the output only if the substitution was successfully done.

EDIT: I've also escaped the final . as suggested in the comments.

Sign up to request clarification or add additional context in comments.

2 Comments

You probably also want to escape the final .
@Douglas: true, I hadn't noticed that (and that's why you don't copy and paste code ;-)
0

Try this?

basename /sdd/ee/publ/xmlfile_555.xml | awk -F_ '{print $2}'

The output is 555.xml

With the other one.

basename /sdd/ee/publ/xmlfile.xml | awk -F_ '{print $2}'

The output is an empty string.

1 Comment

It wasn't meant to be an "out of the box solution" as much as a possible approach but yeah, your're right.
0
$ path=/sdd/ee/publ/xmlfile_555.xml
$ echo ${path##*/}
xmlfile_555.xml
$ path=${path##*/}
$ echo ${path%.xml}
xmlfile_555
$ path=${path%.xml}
$ echo ${path##*_}
555

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.