Thursday, April 28, 2011

How to repeat a few characters a few times in bash?

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 a few times.

Is there a bash shorthand for repeating a pattern?

From stackoverflow
  • #!/bin/bash
    
    function repeat {
        for ((i=0;i<$2;++i)); do echo -n $1 " "; done
    }
    
    convert $(repeat image.png 3) many_images.png
    
  • You can do this using brace expansion:

    convert image.png{,,} many_images.png
    

    will produce:

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

    Brace expansion will repeat the string(s) before (and after) the braces for each comma-separated string within the braces producing a string consiting of the prefix, the comma-separated string and the suffix; and separating the generated strings by a space.

    In this case the comma-separated string between the braces and the suffix are empty strings which will produce the string image.png three times.

    Philipp : This is the best solution for a fixed, small number of repetitions, but doesn't work well for a large or flexible number of repetitions.
    BastiBechtold : This is neat. I like this. But as Philipp mentioned, I kind of have to prefer a parametrized solution.
  • Here is a solution that uses arrays and is thus robust for strings containing spaces, newlines etc.

    declare -a images
    declare -i count=5
    for ((i=0; i<count; ++i))
    do
        images+=(image.png)
    done
    convert "${images[@]}" many_images.png
    
    Dennis Williamson : You can get by without the `declare` statements. In your example, Bash will do the right thing for you. You would just set your count like this: `count=5`. The array will be created by virtue of the parentheses.
  • 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
    
    smichak : Yep - that's it...

0 comments:

Post a Comment