How to do a circular shift of strings in bash?
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
To get you started, check out the read
builtin:
while read first_word rest_of_the_line; do
... your code here ...
done
You also need a way to feed your input file into that loop.
Let me allow to show you a quick working example based on @outis answer:
strings="string1 string2 string3"
next() { echo $1; }
rest() { shift; echo $*; }
for i in $strings; do
echo $(next $strings)
strings=$(rest $strings)
done
Or other way-round if you're interested in traversing by sequence:
strings="string1 string2 string3"
next() { echo $1; }
rest() { shift; echo $*; }
totalWords=$(c() { echo $#; }; c $strings)
for i in `seq -w 1 $totalWords`; do
echo $i: $(next $strings)
strings=$(rest $strings)
done