2010-04-18 59 views
0

我有一個文件由空格分隔。 我需要編寫一個awk命令來接收主機名稱參數 並且它應該替換主機名,如果它已經在文件中定義了。 它必須完全匹配而不是部分 - 如果文件包含此主機名:localhost 搜索「ho」將失敗並將其添加到文件末尾。如何從文件中刪除一行使用awk過濾某些字符串

另一個選項是delete:awk接收主機名參數,如果存在,它應該從文件中刪除它。

這是我到目前爲止有:(它需要一些改進)

if [ "$DELETE_FLAG" == "" ]; then 
     # In this case the entry should be added or updated 
     # if clause deals with updating an existing entry 
     # END clause deals with adding a new entry 
     awk -F"[ ]" "BEGIN { found = 0;} \ 
       { \ 
         if ($2 == $HOST_NAME) { \ 
           print \"$IP_ADDRESS $HOST_NAME\"; \ 
           found = 1; \ 
         } else { \ 
           print \$0; \ 
         } \ 
       } \ 
       END { \ 
         if (found == 0) { \ 
           print \"$IP_ADDRESS $HOST_NAME\"; 
         } \ 
       } " \ 
     /etc/hosts > /etc/temp_hosts 

else 
     # Delete an existing entry 
     awk -F'[ ]' '{if($2 != $HOST_NAME) { print $0} }' /etc/hosts > /etc/temp_hosts 
fi 

感謝

回答

0

你沒有設置FS空間,因爲默認情況下FS已經空間。而且您不必使用\。使用-v選項將shell變量傳遞給awk。而且也沒有必要使用分號結束在每條語句

if [ "$DELETE_FLAG" == "" ]; then 
     # In this case the entry should be added or updated 
     # if clause deals with updating an existing entry 
     # END clause deals with adding a new entry 
     awk -v hostname="$HOST_NAME" -v ip="$IP_ADDRESS" 'BEGIN { found = 0} 
     { 
      if ($2 == hostname) { 
       print ip" "hostname 
       found = 1 
      } else { 
       print $0 
      } 
     } 
     END { 
      if (found == 0) { 
        print ip" "hostname 
      } 
     }' /etc/hosts > /etc/temp_hosts 

else 
     # Delete an existing entry 
     awk -v hostname="$HOST_NAME" '$2!=hostname' /etc/hosts > /etc/temp_hosts 
fi 
+0

謝謝,這種修改的確有竅門! – embedded 2010-04-19 08:52:51

0

你應該把的awk腳本單引號內,並使用變量傳遞拿到shell變量到awk腳本。那麼你不必做所有的逃跑。我不認爲連續反斜槓和分號是必要的。

字段分隔符是空格還是它們是方括號內的空格?

awk -F ' ' -v awkvar=$shellvar ' 
    BEGIN { 
     do_something 
    } 
    { 
     do_something_with awkvar 
    }' file > out_file 

此外,如果變量包含以短劃線開頭的字符串,則測試將失敗。至少有幾種方法可以防止這種情況發生:

if [ "" == "$DELETE_FLAG" ]; then # the dash isn't the first thing that `test` sees 
if [ x"$DELETE_FLAG" == x"" ]; then # ditto 
相關問題