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

 echo $file | .....


  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
  • this isnt typical xml file -:) – yael Jan 2 '13 at 12:25

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.


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

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

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

case $file in
  *.xml) echo "matched $file";;
  *) echo "skipping $file";;

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

$ echo $file
$ echo ${file%.xml*}.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

Or, on a single line

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

easiest way ...

echo  file=machine_configuration.xml | cut -d '.' -f 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.