In Linux: How to repeat multiple lines in a file i

2019-09-06 11:57发布

The input file contains below lines:

a
b
c

I want the output as(n times):

a
b
c
a
b
c

I've tried below command but it doesn't maintain the order

while read line; do for i in {1..4}; do echo "$line"; done; done < file

but the output is

a
a
b
b
c
c

标签: linux bash text
4条回答
别忘想泡老子
2楼-- · 2019-09-06 12:10

printf and brace expansion can be used to repeat a string N times, which can then be passed as input to cat which does its job of concatenate

$ printf "file %.s" {1..4}
file file file file $ 

$ cat $(printf "file %.s" {1..4})
a
b
c
a
b
c
a
b
c
a
b
c


With perl, if file is small enough for memory requirements to be slurped whole

$ perl -0777 -ne 'print $_ x 2' file 
a
b
c
a
b
c
查看更多
等我变得足够好
3楼-- · 2019-09-06 12:14

Using seq with xargs:

seq 2 | xargs -Inone cat file
查看更多
聊天终结者
4楼-- · 2019-09-06 12:17

A small solution for printing file 3 times:

cat $(yes file | head -n 3)

The command substitution $() expands to cat file file file. This works only for filenames without whitespace. Set IFS=$'\n' if your file name contains spaces or tabulators.

查看更多
劳资没心,怎么记你
5楼-- · 2019-09-06 12:23

Another solution could be

#multicat count filename(s)
multicat() {
        local count=$1
        shift
        for((i=0;i < $count; i++)) {
                cat "$@"
        }
}

multicat 3 abc          # outputs the "abc" file 3 times
查看更多
登录 后发表回答