Using Regex groups in bash
Greetings,
I've got a directory with a list of pdfs in it:
file1.pdf, file2.pdf, morestuff.pdf ... etc.
I want to convert these pdfs to pngs, ie
file1.png, file2.png, morestuff.png ... etc.
The basic command is,
convert from to
,
But I'm having trouble getting convert to rename to the same file name. The obvious 'I wish it worked this way' is
convert *.pdf *.png
But clearly that doesn't work. My thought process is that I should utilize regular expression grouping here, to say somethink like
convert (*).pdf %1.png
but that开发者_StackOverflow社区 clearly isn't the right syntax. I'm wondering what the correct syntax is, and whether there's a better approach (that doesn't require jumping into perl or python) that I'm ignoring.
Thanks!
for files in *.pdf
do
if [ -f "$files" ];then
convert "$files" "${files%.pdf}.png"
fi
done
if you need to do it recursively,
find /path -type f -iname "*.pdf" | while read -r FILE
do
convert "$FILE" "${FILE%.pdf}.png"
done
If you really wanted to use regex, Bash≥3.1 supports regular expressions.
for f in *.pdf; do
[[ $f =~ ^(.*)\.pdf$ ]] &&
convert "$f" "${BASH_REMATCH[1]}.png"
done
And all systems should have the shell utility expr
.
for f in *.pdf; do
match=$(expr "$f" : '\(.*\)\.pdf$') &&
convert "$f" "$match.png"
done
But Bash's parameter expansion (as demonstrated in the other answers) works better for simple cases like this.
for f in *.pdf
do
convert "$f" "${f%.pdf}.png"
done
ls *.pdf | sed 's/\"/\\"/;s/^\(.*\).pdf$/convert "&" "\1.png"/' | bash
精彩评论