shell - 如何使用 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
?
解决方案
您正在尝试重命名服务器上的文件,但您只知道下载文件后要运行哪些命令。
简单的选择是运行两个 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
推荐阅读
- java - ManyToMany - JPA - 如何从映射生成的表中获取数据?
- css - javascript google map 缩放到零时为空的灰色背景
- javascript - 如何在 Javascript 中获取 CSS 值并将其保存为变量?
- c# - 如何将选定的复选框移动到复选框列表的顶部
- c++ - 为什么vector会导致Segmentation fault Error?
- php - Websockets 不能通过 TLS/SSL 工作,但可以在没有 TLS/SSL 的情况下工作
- node.js - 使用 node-oracledb executeMany 删除多条记录
- css - 如何为特定组件添加 html、body 选择器样式?
- android - 对话处于活动状态时如何更改状态栏颜色?
- javascript - 使用 Javascript 和 HTML 显示弹出窗口