Linux

使用 shell 腳本處理文本文件並創建命令

  • November 1, 2018

我有一個包含伺服器和域名的文件,如下所示。

名稱.txt:

ABCDomain ContractABCServer_1
ABCDomain ABC_server1
LinkDomain CoreLinkServer_1
TADDomain TADServer_1

(在對其他文件執行排序和唯一操作後,我得到了上面的文件。)—只是附加資訊

我需要從上述文件中提取值並將其作為以下格式的參數傳遞給 xyz 命令(該命令用於重新啟動伺服器)。

輸出/輸出:

"ABCDomain(server:ContractABCServer_1,server:ABC_server1)","LinkDomain(server:CoreLinkServer_1)","TADDomain(TADServer_1)"

我正在使用下面陳述的邏輯,但它並沒有給我想要的輸出,因為域名必須為每組只出現一次。我也很難保持同一條線。

          • -開始 - - -
   DOMAIN=''

IFS=' '
while read line
do
       DOMAIN=$(echo "$line" | awk -F " " '{print $1}')

       for word in $line
       do
               if [[ "$word" == "$DOMAIN" ]]; then
                       Server=$(echo "$line" | awk -F " " '{print $2}' )
                       echo -n "(server:$ServerName"
               fi

       done

done < Names.txt
{
   if (dom[$1]) 
       dom[$1]=dom[$1]","$2
   else 
       dom[$1]=$2
} 

END {
   ORS=",";
   for (d in dom)
       if (d)
           print ("\""d"(server:"dom[d]")""\"")
}

這是快速而骯髒的 awk 解決方案。像 something.awk 一樣保存它,然後執行:

awk -f something.awk Names.txt 

快速修復您的評論

{ dom[$1]=dom[$1] ? dom[$1]",server:"$2 : "server:"$2 }

END {
   for (d in dom)
       if (d) {
           out && out = out","
           out = out"\""d"("dom[d]")""\""
       }
       print out
}

您可以直接將逗號分隔的字元串組合起來awk並在最後列印複合:

 $1 == "ABCDomain"  {d = (d == "") ? $2 : d "," $2; next} 
 $1 == "LinkDomain" {l = (l == "") ? $2 : l "," $2; next} 
 $1 == "TADDomain"  {t = (t == "") ? $2 : t "," $2; next} 

 END {
   printf("\"ABCDomain(server:%s)\",\"LinkDomain(server:%s)\",\"TADDomain(%s)\"\n", d, l, t)
 }

前任。

$ awk '
 $1 == "ABCDomain"  {d = (d == "") ? $2 : d "," $2; next} 
 $1 == "LinkDomain" {l = (l == "") ? $2 : l "," $2; next} 
 $1 == "TADDomain"  {t = (t == "") ? $2 : t "," $2; next} 

 END {
   printf("\"ABCDomain(server:%s)\",\"LinkDomain(server:%s)\",\"TADDomain(%s)\"\n", d, l, t)
 }' Names.txt
"ABCDomain(server:ContractABCServer_1,ABC_server1)","LinkDomain(server:CoreLinkServer_1)","TADDomain(TADServer_1)"

引用自:https://unix.stackexchange.com/questions/450596