You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用xargs向secondCommand传递从其他命令获取的两个参数?

解决方案

当然可以用xargs实现,这里提供两种可行的写法:

方法1:xargs分组传递+shell命令构造

firstCommand | tail -n1 | xargs -n2 sh -c 'secondCommand "$1" --second "$2"' _
  • tail -n1 提取firstCommand输出的最后一行
  • xargs -n2 将该行的两个字段作为一组参数传递
  • sh -c 用来构造目标命令格式,$1对应第一个字段,$2对应第二个字段;末尾的_是占位符,用来占据sh -c命令的$0位置

方法2:awk格式化后配合xargs替换

firstCommand | tail -n1 | awk '{print $1 "@@@" $2}' | xargs -I{} sh -c '
  arg1=$(echo {} | cut -d"@@@" -f1)
  arg2=$(echo {} | cut -d"@@@" -f2)
  secondCommand "$arg1" --second "$arg2"
'
  • 先用awk把两个字段用特殊分隔符(比如@@@,避免和字段内空格冲突)拼接成一行
  • 再通过xargs替换占位符,在shell脚本里拆分出两个参数并调用目标命令

额外:不用xargs的简化写法

如果不局限于xargs,直接用awk调用system命令更简洁:

firstCommand | tail -n1 | awk '{system("secondCommand \"" $1 "\" --second \"" $2 "\"")}'

内容的提问来源于stack exchange,提问作者Emel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 12:20:50