Home > Net >  Bash script to produce a "circular string"?
Bash script to produce a "circular string"?

Time:06-07

Sorry for the awful title -- not sure how else to describe what I want to achieve.

Been trying to make a Bash script for the past couple days to achieve a very simple effect, but I cannot figure out how!

The command line arguments for the script are: (1) a string of length n, (2) an integer "target length" N, and (3) an integer offset M. Additionally, it can be assumed that M,N < n. All I need the program to do is the following:

  1. If M N < n, it should print N chars of the string starting at index M. ./script.sh "Hello world!" 5 3 should print lo wo, ./script.sh "Hello world!" 9 0 should print Hello wor, etc.

  2. Otherwise (i.e. if M N >= n), it should print up to the end of the string, followed by however many chars from the start of the string are required to meet the target length N. ./script.sh "Hello world!" 5 10 should print d!Hel, ./script.sh "Hello world!" 11 6 should print world!Hello, etc.

The resulting effect is a string that is either cut off short or "wrapped" such that it is always of the target length N.

It is step #2 in particular that is what has me stumped. I'm sure it's probably a simple case of doing some fancy stuff with substring syntax, but I've yet to figure it out. I would love to post code, but I haven't even thought of the pseudocode that would make this work yet; that's how stuck I am..

CodePudding user response:

Given the assumption that M and N are less than the length of the string, this becomes really easy. The actual length of the string doesn't matter; if you repeat it twice in a row, any substring using the values of N and M will be in range and doesn't need checks to see if it wraps or not:

#!/usr/bin/env bash                                                                                                                                                                                                                                      

circular() {
    local str="$1$1"
    printf "%s\n" "${str:$3:$2}"
}

str='Hello world!'
circular "$str" 9 0
circular "$str" 5 3
circular "$str" 5 10
circular "$str" 11 6
  •  Tags:  
  • bash
  • Related