重复文件的内容,直到达到规定的行数 [英] Repeat a file content until reach a defined line count

查看:166
本文介绍了重复文件的内容,直到达到规定的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个文件,例如下一个 file.txt的

Have a file such the next file.txt

line-01
line-02
line-03
line-04
line-05
line-06
line-07
line-08
line-09
line-10

这包含10个线条均匀,真正的文件有不同的内容,不同linecounts。

This contains 10 uniform lines, the real files has different content and different linecounts.

需要重复这个文件的内容,UTIL达到定义行计数。

Need repeat the content of this file, util reaching a defined line count.

试了下脚本:

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

repcat file.txt | head -20

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

It works, prints 20 lines, but never ends, need terminate with CTRL-C.

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

Why the repcat continues to write into the pipe, in a case nobody reading its result?

要更奇怪的,增加一个回声猫后

To be more strange, adding one echo after the cat

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

repcat file.txt | head -20

脚本结束。

不明白为什么这样的行为。

Doesn't understand why such behavior.

推荐答案

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

When cat gets an error writing to the pipe, it simply exits, and the script continues to the next loop. Try checking whether cat succeeds:

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

它的工作原理与其他回声的原因是因为回声是一个外壳内置。当它得到一个错误终止它的作用。

The reason it works with the additional echo is because echo is a shell built-in. When it gets an error it terminates the function.

这篇关于重复文件的内容,直到达到规定的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆