[英]how to delete a line from file using awk filtered by some string
我有一個用空格分隔的文件。 我需要編寫一個接收主機名參數的awk命令,如果文件中已經定義了主機名,它應該替換主機名。 它必須是完全匹配的內容,而不是部分匹配的內容-如果文件包含以下主機名:本地主機搜索“ ho”將失敗,並將其添加到文件末尾。
另一個選擇是刪除: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
謝謝
您不必將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
您應該將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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.