Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

bash - How to use both a variable and a changed variable in the same command

in simple I want to execute one command over many files and am trying to do that with a for do done loop.

dwebp foo.webp -o ./PNGs/foo.png is the command that I want to execute over all files that correspond to *.webp in my current directory.

I am able to get the /PNGs/foo.png working by doing

for f in *.webp; do echo "$f" "${f%.webp}.png"; done. I'm now however not able to use $f as the original file name (which is still needed).

The fact that I am using the ${f%.webp}.png without really understanding why or how it works doesn't help... So, does anyone know how I'd be able to run the dwebp foo.webp -o ./PNGs/foo.png command with a for do done loop, or a better way to achieve the same thing?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For an explanation on how ${f%.webp} works, see Parameter Expansion.

${f%.webp} does not modify the value of ${f}, consider:

$ f=foo.webp
$ echo "${f%.webp}.png"
foo.png
$ echo "${f}"
foo.webp

Net result is that you could try something like:

for f in *.webp
do
    echo "${f}"
    dwebp "${f}" -o "./PNGs/${f%.webp}.png"
done

Or if you'll need to perform the same parameter expansion a few times, you can do it once and store in a new variable, eg:

for f in *.webp
do
    newf="${f%.webp}.png"
    echo "original file : ${f} / new file : ${newf}"

    dwebp "${f}" -o "./PNGs/${newf}"
done

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...