拥有一个类似于下一个file.txt的文件
line-01
line-02
line-03
line-04
line-05
line-06
line-07
line-08
line-09
line-10这包括10个统一的行,真正的文件有不同的内容和不同的线条。
需要重复此文件的内容,以达到定义的行计数。
尝试了下一个脚本:
repcat() {
while :
do
cat $1
done
}
repcat file.txt | head -20它工作,打印20行,但永不结束,需要终止与CTRL。
为什么repcat继续写入管道,在没有人读取其结果的情况下?
更奇怪的是,在echo之后添加一个cat
repcat() {
while :
do
cat $1
echo xxx
done
}
repcat file.txt | head -20剧本结束了。
不明白为什么会有这种行为。
发布于 2014-04-02 17:36:16
当cat收到写入管道的错误时,它只是退出,脚本继续到下一个循环。尝试检查cat是否成功:
repcat() {
while cat "$1"
do
:
done
}它与附加echo一起工作的原因是因为echo是一个内置的shell。当它得到错误时,它将终止该函数。
发布于 2014-04-02 18:33:41
您还可以使用:
yes "$(< file.txt)" | head -n 20发布于 2014-04-02 18:09:19
以下是另一种方法:
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
twohttps://stackoverflow.com/questions/22818814
复制相似问题