首页 > 解决方案 > 如何使用 printf 运行从 awk 生成的命令?

问题描述

我想创建一个 shell 脚本,该脚本将.txt使用 SFTP 重命名远程服务器中特定目录中的所有文件(将首先下载文件,然后在远程服务器中重命名)。请检查以下尝试:

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

标签: shellawk

解决方案


您正在尝试重命名服务器上的文件,但您只知道下载文件后要运行哪些命令。

简单的选择是运行两个 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

推荐阅读