3

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

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.

1

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
0

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
-1

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.