Reputation: 85
I need to create a code where i take all the files in the current directory ending with *.txt, *.jpg, *.conf. After i collect those i need to check if they contain a certain line which is:
<?xml version="1.0" encoding="UTF-8"?>
if they do contain the following line, then i need to rename them to *.xml.
My question is: How do i check with regex in an if statement if the file contains the given regex code?
My current code:
ls *.txt *.data *.conf
for f in *.*
case $f in
*.txt)
if [[ "$(grep -q '<\?xml version="[0-9]*.[0-9]*" encoding=".*"\?>' *.txt) ]]; then
mv -- "$f" "${%f.txt].xml"
fi
;;
esac
done
ls
the code for *.jpg) and *.conf) would be the same. Any help is appreciated.
Upvotes: 3
Views: 52
Reputation: 784898
You may use:
for f in *.txt *.data *.conf; do
if grep -iq '<?xml version="[0-9]*\.[0-9]*" encoding="[^"]*"?>' "$f"; then
mv "$f" "${f%.*}.xml"
fi
done
-q
option in grep
is for the quiet mode.
Upvotes: 5