0

I have a shell script for renaming multiple files in a folder. It works on a rhel host but throws error on a ubuntu14 host.

#!/usr/bin/env bash

SOME_NUMBER=1
rename _file_name.c _file_${SOME_NUMBER}.c path/of/file/*_file_name.c

What changes shall i make in the code to make it work on a ubuntu14 host?

EDIT-1:

For running the code on ubuntu machine i made following change and it works:

rename 's/\_file_name.c$/\_file_1.c/' path/of/file/*_file_name.c

but following doesn't works and i get below error message:

rename 's/\_file_name.c$/\_file_${SOME_NUMBER}.c/' path/of/file/*_file_name.c

ERROR MESSAGE:

Global symbol "$SOME_NUMBER" requires explicit package name at (eval 1) line 1.
Global symbol "$SOME_NUMBER" requires explicit package name at (eval 1) line 1.
Yash
  • 2,944
  • 7
  • 25
  • 43
  • That's a `perl` error message, not `bash`. But `${SOME_NUMBER}` will be exxpanded by the shell, it should never be seen by `perl`. – Barmar Nov 06 '18 at 17:41
  • Is that an exact copy of the script? You'd get that error if `_file_${SOME_NUMBER}.c` was in single quotes. – Barmar Nov 06 '18 at 17:42
  • you are correct Barmar. I have edited the problem statement. – Yash Nov 06 '18 at 17:49
  • Do you know @ShijithR? They posted a very similar question 1 hour ago (they've since deleted it), and also posted the wrong types of quotes in the question. – Barmar Nov 06 '18 at 21:53

1 Answers1

2

Single quotes prevent parameter expansion. Because Perl and shell syntax is similar in this regard, the literal string s/\_file_name.c$/\_file_${SOME_NUMBER}.c/ is passed to Perl, where it tries to expand the undefined variable $SOME_NUMBER.

Use double quotes instead:

rename "s/\_file_name.c$/\_file_${SOME_NUMBER}.c/" path/of/file/*_file_name.c

See Difference between single and double quotes in Bash

Be sure that the value of SOME_NUMBER in your shell script really is just a number, or at least something that, when expanded, produces a valid Perl expression.

Barmar
  • 741,623
  • 53
  • 500
  • 612
chepner
  • 497,756
  • 71
  • 530
  • 681