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!
You just need to tell
sedto keep its mouth shut if it doesn’t find a match. The-noption is used for that.I only made two changes to what you had: the aforementioned
-noption tosed, and thepflag that comes after thes///command, which tellssedto print the output only if the substitution was successfully done.EDIT: I’ve also escaped the final
.as suggested in the comments.