2017-04-12 111 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

相关问题