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

2019-09-06 11:58发布

问题:

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

回答1:

Using seq with xargs:

seq 2 | xargs -Inone cat file


回答2:

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


回答3:

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


回答4:

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.



标签: linux bash text