【问题标题】:Running a command on each id in a text file对文本文件中的每个 id 运行命令
【发布时间】:2013-04-21 01:26:09
【问题描述】:

我有一个包含如下 id 列表的文本文件,我需要对每个这些 id 运行以下命令,在 awk 中是否有更简单的方法?

ssh -p 29418 company.com gerrit review --code-review 2 -- file.txt

file.txt 包含以下内容:

297003
297002
297001
...

只要 file.text 中存在 id,就应该运行以下命令

ssh -p 29418 company.com gerrit review --code-review 2 -- 297003
ssh -p 29418 company.com gerrit review --code-review 2 -- 297002
ssh -p 29418 company.com gerrit review --code-review 2 -- 297001
.....

【问题讨论】:

  • 如何“在”他们身上运行它?应该将每个 id 添加到命令行的末尾,还是应该替换命令行中的数字之一?
  • 您为什么要为此使用 awk? Shell 脚本似乎是自然的选择。

标签: linux bash shell awk xargs


【解决方案1】:

我会使用 while 循环对每个值执行操作,并将 $i 的值设置为包含值列表的文件的 read 的输出。

while read i
do
     ssh -p 29418 company.com gerrit review --code-review 2 -- $i
done < filename

正如 sudo_O 所说,您可以使用 echo 命令检查在尝试运行实际代码之前生成的命令。

while read i
do
     echo "ssh -p 29418 company.com gerrit review --code-review 2 -- $i" 
done < filename

【讨论】:

  • 正确的编码方式是while read i; do ... done &lt;file.txt
  • 使用while read i而不是for i in $( cat filename )有什么优势?
  • 我已经意识到自己的坏习惯。感谢您的提示。
【解决方案2】:

Awk 不是我想在这里使用的工具。我建议xargs

xargs -I% -n1 < file ssh -p 29418 company.com gerrit review --code-review 2 -- %

% 字符是使用 -I 选项设置的替换字符串,但是在这种情况下,由于替换位于命令末尾,因此不需要明确说明,因为 xargs 只需附加到默认结束:

xargs -n1 < file ssh -p 29418 company.com gerrit review --code-review 2 --

提示是在实际运行之前使用echo 命令查看输出:

# -------------- notice we run echo not ssh to see the output before we rut it 
xargs -n1 < file echo ssh -p 29418 company.com gerrit review --code-review 2 -- 
ssh -p 29418 company.com gerrit review --code-review 2 -- 297003
ssh -p 29418 company.com gerrit review --code-review 2 -- 297002
ssh -p 29418 company.com gerrit review --code-review 2 -- 297001

如果没有-n1 选项,xargs 将传递所有可能对这种特定情况有用或可能没有用的值,具体取决于gerrit 的使用情况:

xargs < file echo ssh -p 29418 company.com gerrit review --code-review 2 -- 
ssh -p 29418 company.com gerrit review --code-review 2 -- 297003 297002 297001

【讨论】:

  • @sudo_O - 更新了问题..端口号始终不变..file.txt 中每个 id 的“--”选项都会更改
  • @user2125827 这很有意义哈哈。我已经更新了我的答案,% 只是替换为file 中的每个数字,所以% 只是移动到命令的末尾。
【解决方案3】:
while read sshid
do
  ssh -p $sshid ...
done < file.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-11
    相关资源
    最近更新 更多