How to Reverse a String in Bash Script?
I Have a String Like That: |Abcdefg| and I Want to Reverse This String Gfedcba Is That Possible in Bash? 5 1 Answer with Rev Command You Can Reverse the...
I have a string like that:
|abcdefg|
and I want to reverse this String
gfedcba
Is that possible in bash?
1 Answer
With rev command you can reverse the string:
$ echo '|abcdefg|' |rev
|gfedcba|
if you want pure bash solution:
str='|abcdefg|'; for ((i=${#str}-1; i>=0; i--));do printf "${str:$i:1}"; done
${#str}returns the character length of its parameterstr.${str:start:length}picks length characters from its parameterstrfromstartpoint (the first character has index 0).
if you don't want first & last pipe characters, do:
str='|abcdefg|'; for ((i=${#str}-2; i>=1; i--));do printf "${str:$i:1}"; done