2017-04-12 76 views
1

如何通過字符串「BUILD#」循環並僅使用bash腳本打印具有以下字符串「http://」的行? 或我們如何爲字符串「BUILD」 之間有一切input.txt中在文本文件中循環匹配的字符串

BUILD #1 
http://a 
b 
http://c 

BUILD #2 
http://d 
http://c 
http://g 


BUILD #3 
g 
http://h 
http://f 
e 
http://t 

所需的輸出

編者按:作爲證明被接受了什麼樣的答案,這個問題竟然不是要生產已過濾輸出,但有選擇地處理行知道封閉的方式, 如相應的前述BUILD #<n>行暗示。

BUILD #1 (loop) 
http://a 
http://c 
add another loop to do something with http:// 

BUILD #2 (loop) 
http://d 
http://c 
http://g 
add another loop to do something with http:// 

BUILD #3 (loop) 
http://h 
http://f 
http://t 
add another loop to do something with http:// 

input.txt中有合併請求的列表。

BUILD #1 
take the link (integrate) 
take the link (integrate) 
kick of a build (build command) 
BUILD #2 
take the link (integrate) 
take the link (integrate) 
take the link (integrate) 
kick of a build (build command) 
and so on 

回答

3

你可以循環像這樣:

while read -r; do 
    # if current line starts with BUILD then set a variable build with build # 
    [[ $REPLY == BUILD* ]] && build="${REPLY#BUILD }" && continue 

    # if current line starts with http:// then execute a command using build # & link 
    [[ $REPLY == http://* ]] && printf "Build: %s -> Link: %s\n" "$build" "$REPLY" 
done < input.txt 

Build: #1 -> Link: http://a 
Build: #1 -> Link: http://c 
Build: #2 -> Link: http://d 
Build: #2 -> Link: http://c 
Build: #2 -> Link: http://g 
Build: #3 -> Link: http://h 
Build: #3 -> Link: http://f 
Build: #3 -> Link: http://t 

您可以更改printf你想要的任何其他命令。

1

anubhava's helpful answer向您展示瞭如何按順序遍歷行,記錄當前版本號作爲每個特定生產線塊的輸入。

下面是通過構建構建處理線,塊線的解決方案,這樣你就可以構建應用級別的操作,如果需要的話。

全部塊按順序進行處理,但不會很難將解決方案調整爲僅針對特定構建。

#!/bin/bash 

buildNum= urls=() finalIteration=0 
while IFS= read -r line || { finalIteration=1; true; }; do 
    # A new build block is starting or EOF was reached. 
    if [[ $line =~ ^'BUILD #'([0-9]+) || $finalIteration -eq 1 ]]; then 
    if [[ $buildNum ]]; then # Process the previous block. 
     echo "Processing build #$buildNum..." 
     # Process all URLs. 
     i=0 
     for url in "${urls[@]}"; do 
     echo "Url #$((++i)): $url" 
     done 
     # Add further per-build processing here... 
    fi  
    ((finalIteration)) && break # Exit the loop, if EOF reached. 
    # Save this block's build number. 
    buildNum=${BASH_REMATCH[1]} 
    urls=() # Reset the array of URLs. 
    # Collect the lines of interest in array ${url[@]}, for later processing. 
    elif [[ $line =~ ^http:// ]]; then 
    urls+=("$line") 
    fi 
done < input.txt 
+0

- 非常感謝您的詳細解釋.. – Mihir

相關問題