Derek
Derek

Reputation: 33

How to rename all files over SSH

I am trying to rename all files in a remote directory over SSH or SFTP. The rename should convert the file into a date extension, for example .txt into .txt.2016-05-25.

I have the following command to loop each .txt file and try to rename, but am getting an error:

ssh $user@$server "for FILENAME in $srcFolder/*.txt; do mv $FILENAME $FILENAME.$DATE; done"

The error I am getting is:

mv: missing destination file operand after `.20160525_1336'

I have also tried this over SFTP with no such luck. Any help would be appreciated!

Upvotes: 3

Views: 5469

Answers (3)

F. Hauri  - Give Up GitHub
F. Hauri - Give Up GitHub

Reputation: 70987

Try this:

By using rename ( tool):

ssh user@host /bin/sh <<<$'
    rename \047use POSIX;s/$/strftime(".%F",localtime())/e\047 "'"$srcFolder\"/*.txt" 

To prepare/validate your command line, replace ssh...bin/sh by cat:

cat <<<$'
    rename \047use POSIX;s/$/strftime(".%F",localtime())/e\047 "'"$srcFolder\"/*.txt" 

will render something like:

rename 'use POSIX;s/$/strftime(".%F",localtime())/e' "/tmp/test dir"/*.txt

And you could localy try (ensuring $srcFolder contain a path to a local test folder):

/bin/sh <<<$'
    rename \047use POSIX;s/$/strftime(".%F",localtime())/e\047 "'"$srcFolder\"/*.txt" 

Copy of your own syntax:

ssh $user@$server /bin/sh <<<'for FILENAME in "'"$srcFolder"'"/*.txt; do
     mv "$FILENAME" "$FILENAME.'$DATE'";
  done'

Again, you could locally test your inline script:

sh <<<'for FILENAME in "'"$srcFolder"'"/*.txt; do
    mv "$FILENAME" "$FILENAME.'$DATE'";
done'

or preview by replacing sh by cat.

Upvotes: 1

janos
janos

Reputation: 124784

You need to escape (or single-quote) the $ of variables in the remote shell. It's also recommended to quote variables that represent file paths:

ssh $user@$server "for FILENAME in '$srcFolder'/*.txt; do mv \"\$FILENAME\" \"\$FILENAME.$DATE\"; done"

Upvotes: 2

Inetquestion
Inetquestion

Reputation: 185

When using/sending variables over SSH, you need to be careful what is a local variable and which is a remote variable. Remote variables must be escaped; otherwise they will be interpreted locally versus remotely as you intended. Other characters also need to be escaped such as backticks. The example below should point you in the right direction:

Incorrect

user@host1:/home:> ssh user@host2 "var=`hostname`; echo \$var"

host1

Correct

user@host1:/home:> ssh user@host2 "var=\`hostname\`; echo \$var"

host2

Upvotes: 0

Related Questions