[SOLVED] Shell scripting syntax question

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
benali72
Level 4
Level 4
Posts: 278
Joined: Sat Mar 23, 2013 11:49 am

[SOLVED] Shell scripting syntax question

Post by benali72 »

Hi,

I'm trying to write a shell script, and am having trouble substituting a value dynamically into a rename command.

For a given value assigned to ${value}, here's what I'm trying to do --

rename 's/${value}.webp/webp/g' *

Of course, that doesn't work because of the single quotes. I also tried building the entire string in a separate variable before issuing it as a command, but I wasn't successful at that due to the asterisk (*).

Anyone know how to write this syntax correctly?

Thank you.
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 3 times in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
rene
Level 20
Level 20
Posts: 12212
Joined: Sun Mar 27, 2016 6:58 pm

Re: Shell scripting syntax question

Post by rene »

You don't in fact in this case need any quotes, but generally, double rather than single quotes leave variable expansion intact.

Careful by the way that that . in there means "any character" in a regex whereas it seems likely you in mean to say "a period". Within single or double quotes use \. to escape that period (and without quotes, use \\\. to fist escape the backslash and then the period...)
benali72
Level 4
Level 4
Posts: 278
Joined: Sat Mar 23, 2013 11:49 am

Re: Shell scripting syntax question

Post by benali72 »

Hey, thank you so much.

I didn't realize the single quotes weren't required in the rename command.

With your advice, I got it ---- rename s/${val}\.webp/webp/g *

Cool. Thanks.
rene
Level 20
Level 20
Posts: 12212
Joined: Sun Mar 27, 2016 6:58 pm

Re: [SOLVED] Shell scripting syntax question

Post by rene »

That's as said not completely right yet IF you don't also want to rename the file e.g. <pre>${val}1webp<post> but only <pre>${val}.webp<post>.

That is, without any quotes the \ is interpreted by the shell as escaping . which given that it does not in fact consider . special means it turns \. simply into .. rename therefore still if we assume that val=foo receives foo.webp in which it then interprets that period as "any character". I.e., either use double quotes so as to keep \ from being interpreted by the shell or escape it all double as s/${val}\\\.webp/webp/g.
Locked

Return to “Scripts & Bash”