Search code examples
bashshelltext-parsing

How to do a circular shift of strings in bash?


I have a homework assignment where I need to take input from a file and continuously remove the first word in a line and append it to the end of the line until all combinations have been done.

I really don't know where to begin and would be thankful for any sort of direction.

The part that has me confused is that this is suppose to be performed without the use of arrays. I'm not just fishing for someone to solve the problem for me, I'm just looking for some direction.

SAMPlE INPUT:

Pipes and Filters
Java Swing
Software Requirements Analysis

SAMPLE OUTPUT:

Analysis Software Requirements
Filters Pipes and
Java Swing
Pipes and Filters
Requirements Analysis Software
Software Requirements Analysis
Swing Java

Solution

  • A few tidbits that should help: when you call a function with a string, the string is split into multiple arguments (the positional parameters, named $n, where n are integers starting at 1) on the characters in the variable $IFS (which defaults to spaces, tabs and newlines)

    function first() {
        echo $1
    }
    first one two three
    # outputs: "one"
    

    $* and $@ give you all the positional parameters, in order.

    Second, the special variable $# holds the number of arguments to a function.

    Third, shift discards the first positional parameter and moves up all the others by one.

    function tail() {
        shift
        echo $*
    }
    

    Fourth, you can capture the output of commands and functions using `...` or $(...)

    rest=`tail $*`
    

    Fifth, you can send the output of one command to the input of another using the pipe character (|):

    seq 5 | sort