2017-09-02 65 views
1

輸入我的文字,如: TEXT="I need to replace the hostname [[google.com]] with it's ip in side the text"使用sed的拍攝組變量作爲bash命令

是否有使用類似以下,但工作方式? sed -Ee "s/\[\[(.*)\]\]/`host -t A \1 | rev | cut -d " " -f1 | rev`/g" <<< $TEXT

看起來沒有被傳遞到用於內部sed的外殼命令的\ 1的值。

由於

回答

1

反引號內插由殼,不受sed執行。這意味着在sed命令運行之前,您的反引號將被命令的輸出替換,或者(如果您正確引用它們),它們將不會被替換,並且sed將會看到反引號。

您似乎試圖讓sed執行替換,然後讓shell執行反引號插值。

您可以通過適當引述他們闖過外殼反引號:

$ echo "" | sed -e 's/^/`hostname`/' 
`hostname` 

然而,在這種情況下,你將有權使用shell命令行得到的字符串再次引起反引號插值。

根據你對awk,perl或python的看法,我建議你使用其中的一個來完成這項工作。或者,您可以首先將主機名提取爲不帶反引號的命令,然後執行命令以獲取所需的IP地址,然後在另一個傳遞中替換它們。

1

它必須是一個兩部分命令,一個獲得bash可以使用的變量,另一個使用sed進行直接/ s /替換。

TEXT="I need to replace the hostname [[google.com]] with it's ip in side the text" 
DOMAIN=$(echo $TEXT | sed -e 's/^.*\[\[//' -e 's/\]\].*$//') 
echo $TEXT | sed -e 's/\[\[.*\]\]/'$(host -tA $DOMAIN | rev | cut -d " " -f1 | rev)'/' 

但是,更清潔的使用how to split a string in shell and get the last field

TEXT="I need to replace the hostname [[google.com]] with it's ip in side the text" 
DOMAIN=$(echo $TEXT | sed -e 's/^.*\[\[//' -e 's/\]\].*$//') 
HOSTLOOKUP=$(host -tA $DOMAIN) 
echo $TEXT | sed -e 's/\[\[.*\]\]/'${HOSTLOOKUP##* }/ 

短的版本是,你不能混用SED和bash你希望的方式。

0

這工作:

#!/bin/bash 

txt="I need to replace the hostname [[google.com]] with it's ip in side the text" 
host_name=$(sed -E 's/^[^[]*\[\[//; s/^(.*)\]\].*$/\1/' <<<"$txt") 
ip_addr=$(host -tA "$host_name" | sed -E 's/.* ([0-9.]*)$/\1/') 
echo "$txt" | sed -E 's/\[\[.*\]\]/'"$ip_addr/" 

# I need to replace the hostname 172.217.4.174 with it's ip in side the text 
0

謝謝大家,

我作出了以下解決方案:

function host_to_ip() { 
    echo $(host -t A $1 | head -n 1 | rev | cut -d" " -f1 | rev) 
} 

function resolve_hosts() { 
    local host_placeholders=$(grep -o -e "##.*##" $1) 

    for HOST in ${host_placeholders[@]} 
    do 
     sed -i -e "s/$HOST/$(host_to_ip $(sed -Ee 's/##(.*)##/\1/g' <<< $HOST))/g" $1 
    done 
} 

凡resolve_hosts得到一個文本文件作爲參數