How to repeat multiple characters in bash several times?

In a bash script, I have to include the same file several times in a row as an argument. Like this:

convert image.png image.png image.png [...] many_images.png 

where image.png should be repeated several times.

Is there a bash shorthand for repeating a pattern?

+4
source share
7 answers

This works with a given integer (10 in the example below).

 $ echo $(yes image.png | head -n10) image.png image.png image.png image.png image.png image.png image.png image.png image.png image.png 

It can also be used with xargs :

 $ yes image.png | head -n10 | xargs echo image.png image.png image.png image.png image.png image.png image.png image.png image.png image.png 
+7
source

You can do this using a parenthesis extension:

 convert image.png{,,} many_images.png 

will produce:

 convert image.png image.png image.png many_images.png 

The brace extension will repeat the lines (lines) before (and after) the brackets for each comma-separated line in curly braces, creating a line containing a prefix, a line separated by commas, and a suffix; and dividing the generated lines into a space.

In this case, the line, separated by commas between curly braces and the suffix, is an empty line that will generate the image.png line three times.

+10
source
 #!/bin/bash function repeat { for ((i=0;i<$2;++i)); do echo -n $1 " "; done } convert $(repeat image.png 3) many_images.png 
+2
source

Here is a solution that uses arrays and therefore is resistant to lines containing spaces, lines, etc.

 declare -a images declare -i count=5 for ((i=0; i<count; ++i)) do images+=(image.png) done convert "${images[@]}" many_images.png 
+2
source

This might work for you:

 convert $(printf "image.png %.s" {1..5}) many_images.png 

This will be repeated image.png 5 times until many_images.png

0
source

To avoid slow code that opens unwanted bash instances using the $ (command) or command , you can use the parenthesis extension.

Repeat the file name 3 times:

 file="image.png"; convert "${file[0]"{1..3}"}" many_images.png 

or a more controversial version that uses a variable to indicate the number of duplicate file names:

 n=10; file="image.png"; eval convert \"\${file[0]\"{1..$n}\"}\" many_images.png 

How it works.

$ {file [0]} is the same as $ file or $ {file}

Bash first executes the brace extension, and therefore it makes up this sequence:

 ${file[0]1} ${file[0]2} ${file[0]3} 

Bash kindly ignore these extra numbers to get

 ${file[0]} ${file[0]} ${file[0]} 

Which makes it easier

 ${file} ${file} ${file} 

and then

 $file $file $file 

This is what we want.

0
source

The shortest POSIX 7 solution I have found so far:

 N=3 S="image.png " printf "%${N}s" | sed "s/ /$S/g" 

since yes , seq and {1..3} are not POSIX.

In your specific example:

 N= convert $(printf "%${N}s" | sed "s/ /image.png /g") many_images.png 
0
source

All Articles