基于 awk find from a file 运行命令

基于 awk find from a file 运行命令

我正在尝试运行一些基于使用 awk 从文件中匹配的字符串的命令。我不确定这是否是正确的方法。使用 grep 是否更适合此目的?

#!/bin/bash
file1='ip.txt'
while read line; do 
  if `awk -F: '2 == /puppetclient/'` then 
    echo "Found the IP `awk '{print $1}'` with the text `awk '{print $2}'`"
    echo "Will install puppet agent"
  fi
  if `awk -F: '2 == /puppetmaster/'` then
    echo "Found the IP `awk '{print $1}'` with the text `awk '{print $2}'`"
    echo "Will install puppet server"
  fi
done < $file1

ip.txt

{
52.70.194.83 puppetclient
54.158.170.48 puppetclient
44.198.46.141 puppetclient
54.160.145.116 puppetmaster puppet
}

答案1

我完全不确定为什么你想循环文件而不是直接awk使用

awk '
    /puppetclient/ {
        printf "Found the IP %s with the text %s\n", $1, $2
        printf "Will install puppet agent\n"
        system ("echo agent magic")    # Execute this command
    }
    /puppetmaster/ {
        printf "Found the IP %s with the text %s\n", $1, $2
        printf "Will install puppet server\n"
        system ("echo server magic")    # Execute this command
    }
' ip.txt

答案2

根本不要为此使用 awk,因为它没有任何好处,而且会带来额外的复杂性和低效率。 Shell 的存在是为了操作文件和进程以及对工具的顺序调用,而这正是您正在做的事情 - 编写脚本来对某些命令的调用进行顺序。您不需要从 shell 调用 awk 等外部工具来比较 2 个字符串作为其中的一部分。

只需在 shell 中执行此操作:

#!/usr/bin/env bash
file1='ip.txt'
while read -r ip role rest; do
    case $role in
        puppetclient )
            echo "Found the IP $ip with the text $role"
            echo "Will install puppet agent"
            command_to_install_puppet_agent
            ;;
        puppetmaster )
            echo "Found the IP $ip with the text $role"
            echo "Will install puppet server"
            command_to_install_puppet_server
            ;;
    esac
done < "$file1"

相关内容