Multiplying strings in bash script

前端 未结 5 2180
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 20:59

I know that if I do print (\"f\" + 2 * \"o\") in python the output will be foo.

But how do I do the same thing in a bash script?

5条回答
  •  难免孤独
    2020-12-16 21:28

    In bash you can use simple string indexing in a similar manner

    #!/bin/bash
    oos="oooooooooooooo"
    n=2
    printf "%c%s\n" 'f' ${oos:0:n}
    

    output

    foo
    

    Another approach simply concatenates characters into a string

    #!/bin/bash
    n=2
    chr=o
    str=
    for ((i = 0; i < n; i++)); do 
        str="$str$chr"
    done
    printf "f%s\n" "$str"
    

    Output

    foo
    

    There are several more that can be used as well.

提交回复
热议问题