重复文件内容,直到达到定义的行数

时间:2014-04-02 17:32:22

标签: bash

拥有下一个file.txt

这样的文件
line-01
line-02
line-03
line-04
line-05
line-06
line-07
line-08
line-09
line-10

这包含10条统一的行,真实文件具有不同的内容和不同的行数。

需要重复此文件的内容,util达到定义的行数。

尝试了下一个脚本:

repcat() {
    while :
    do
        cat $1
    done
}

repcat file.txt | head -20

它工作,打印20行,但永远不会结束,需要用CTRL-C终止。

为什么repcat继续写入管道,在没有人读取结果的情况下?

更奇怪的是,在echo

之后添加一个cat
repcat() {
        while :
        do
                cat $1
                echo xxx
        done
}

repcat file.txt | head -20

脚本结束。

不明白为什么会这样做。

3 个答案:

答案 0 :(得分:5)

cat写入管道时出错,它只是退出,脚本继续下一个循环。尝试检查cat是否成功:

repcat() {
    while cat "$1"
    do 
        :
    done
}

它与其他echo一起使用的原因是因为echo是内置的shell。当它出错时它会终止该函数。

答案 1 :(得分:2)

你也可以使用:

yes "$(< file.txt)" | head -n 20

答案 2 :(得分:1)

这是另一种方法:

rephead () { 
    local n=$1; shift        
    if (($# > 0)); then
        input=$(cat "$@")
    else
        input=$(cat -)
    fi
    local lines=$(wc -l <<< "$input")
    local count=0
    while ((count < n)); do
        echo "$input"
        ((count += lines))
    done | head -n $n
}

测试:

$ seq 3 | rephead 10
1
2
3
1
2
3
1
2
3
1

和文件

$ cat f1
one
two 
three
four
$ cat f2
a
b
c
d
$ rephead 10 f1 f2
one
two
three
four
a
b
c
d
one
two