我想创建一个Shell脚本,该脚本将使用SFTP重命名远程服务器中特定目录中的所有.txt
文件(先下载文件,然后在远程服务器中重命名)。请检查以下尝试:
sftp user@host <<EOF
cd $remoteDir
get *.txt
ls *.txt | awk '{printf "rename %s %s.done\n",$0,$0 ;}'
exit
EOF
它将根据语句ls *.txt | awk '{printf "rename %s %s.done\n",$0,$0 ;}'
生成并打印出rename
命令列表,我的问题是,如何运行从awk
printf
生成的这些命令? / p>
答案 0 :(得分:0)
您正在尝试重命名服务器上的文件,但是您只知道下载文件后要运行什么命令。
简单的选择是运行两个sftp会话。首先下载文件。然后生成重命名命令。然后,您运行第二个sftp会话。
但是可以在一个会话中同时进行这两个操作:
#!/bin/bash
(
# clean up from any previous run
rmdir -f syncpoint
# echo commands are fed into the sftp session
# be careful with quoting to avoid local shell expansion
echo 'cd remoteDir'
echo 'get *.txt'
echo '!mkdir syncpoint'
# wait for sftp to create the syncpoint folder
while [ ! -d syncpoint ]; do sleep 5; done
# the files have been downloaded
# now we can generate the rename commands
for f in *.txt; do
# @Q is a bash (v4.4+) way to quote special characters
echo "rename ${f@Q} ${f@Q}.done"
# if not available, single-quoting may be enough
#echo "rename '$f' '$f'.done"
done
# clean up
rmdir syncpoint
) | sftp user@host
答案 1 :(得分:-3)
你好新手,请使用此
sftp user@host <<EOF
cd $remoteDir
ls *.txt | awk '{printf "mv %s %s.done\n",$0,$0 ;}' | sh
exit
EOF