简体   繁体   English

Bash 从渐进循环的 output 打印 n 行数

[英]Bash Print n nunber of lines from the output of progressive loop

Case Scenario: My script contains a loop that produces x number of lines, and after each loop x increases may be doubled or tripled etc. I want to print n number of lines from the output but without any halt.案例场景:我的脚本包含一个产生 x 行数的循环,并且在每个循环后 x 增加可能会增加一倍或三倍等。我想从 output 打印 n 行但没有任何停止。

eg.例如。

fun() { unset var res; var=$1; while true; do res=$(seq $var); printf "%s\n" $res; let var++; done; }
fun 1
Output:
1
1
2
1
2
3
1
2
3
4
1
2
3
4
5
.
.
.
Infinite Loop

Controlling above loop via通过控制上述循环

fun() { unset var res; var=$1; start=1; while true; do until [[ $start == $2 ]]; do res=$(seq $var); printf "%s\n" $res; let var++; let start++; done; if [[ $start == $2 ]]; then break; fi; done; }

fun 5 3 #only first 3 lines of fun 5 should be outputted Controlling the number of time loop is runned is not option; fun 5 3 #仅输出 fun 5 的前 3 行 控制运行时间循环的次数不是选项; since as shown above after every loop output lines are increased;因为如上所示,在每个循环 output 行增加之后; ( first time only 1; then 1 2; then 1 2 3...), so fun 5 3 will not print 3 line I want to print n number of lines from that output. (第一次只有 1;然后 1 2;然后 1 2 3...),所以很有趣 5 3 不会打印 3 行我想从 output 打印 n 行。

eg.例如。 fun 5 $max; #where $max is number of lines i wanted to print
Dont want to use 3rd party tool, want in pure bash不想使用第三方工具,想要纯 bash

Tried emulating head with尝试用

head 5 15 15;头 5 15 15; shoul print only 5 line from output But for long number means long $2 $3 ($1 for fun);应该从 output 仅打印 5 行但是对于长数字意味着长 $2 $3($1 娱乐); it halts.它停止了。 I wanted a non halting continuous output.我想要一个不间断的连续 output。 Start looping and printf but stop at defined $max line.开始循环和 printf 但在定义的 $max 行处停止。

Maybe using named pipe works也许使用名为 pipe 的作品
Can someone help me with this有人可以帮我弄这个吗

Pipe to a function that emulates head followed by one that emulates cat > /dev/null . Pipe 到模拟head的 function 后跟模拟cat > /dev/null的 function 。

myhead() {
    for ((i = 0; i < $1; i++)); do
        read -r line
        printf "%s\n" "$line"
    done
}
catnull() {
    while read -r line; do :; done
}
fun 1 | { myhead 5; catnull; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM