Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How to verify if the name of a .xml file name ended with .any-string? e.g. .previous or .backup or bck12 etc ...

I need to print the XML file name except for XML files that end with .any-string or have anything after the .xml

How to verify this with grep or awk or sed or perl or any other idea? Something like

 file=machine_configuration.xml
 file=machine_configuration.xml.previos
 file=machine_configuration.xml.backup
 echo $file | .....

Examples:

  1. machine_configuration.xml: yes
  2. machine_configuration.xml.OLD: no
  3. `machine_configuration.xml-HOLD: no
  4. machine_configuration.xml10: no
  5. machine_configuration.xml@hold: no
  6. machine_configuration.xml_need_to_verifi_this: no
share|improve this question
    
this isnt typical xml file -:) –  yael Jan 2 '13 at 12:25
add comment

3 Answers

up vote 1 down vote accepted

Use the regex end-anchor ($), e.g.:

echo "$file" | grep '\.xml$'

To find all files ending with "xml", I would suggest using the find command, e.g.:

find . -name '*.xml'

Would recursively list all xml files from current directory.

share|improve this answer
add comment

If you have the filename in a variable already, a good approach would be parameter expansion

$ echo $file
text.xmllsls
$ echo ${file%.xml*}.xml
text.xml

Where the %.xml* is that the last occurrence of .xml and everything behind it will be deleted. Therefor I also echoed a .xml again.

Or, to have the test as well

$ file=test.xmlslsls
$ file2=${file%.xml*}.xml
$ if [ $file = $file2 ]; then echo $file; fi
$
$
$ file="test.xml"
$ file2=${file%.xml*}.xml
$ if [ $file = $file2 ]; then echo $file; fi
test.xml

Or, on a single line

$ if [ $file = ${file%.xml*}.xml ]; then echo $file; fi
share|improve this answer
add comment

If I understand correctly, you want to detect whether a file name ends in .xml.

case $file in
  *.xml) echo "$file";;
esac

If you want to do something when the file name doesn't match:

case $file in
  *.xml) echo "matched $file";;
  *) echo "skipping $file";;
esac
share|improve this answer
add comment

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.