How to rename all files over SSH

别来无恙 提交于 2019-12-12 18:28:26

问题


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!


回答1:


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"



回答2:


Try this:

By using rename (perl 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.




回答3:


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



来源:https://stackoverflow.com/questions/37444322/how-to-rename-all-files-over-ssh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!