We are given a string and we have to use shell script print it in the reverse order. Asked in FICO Examples:
Input : geeksforgeeks Output :skeegrofskeeg
Algorithm
step 1:- Take user input in a string step 2:- Findthe length of given string using length function step 3:- Set i = length-1 and run loop till i <= 0 step 4:- echo the $i step 5:- repeat step 3 and 4 till i==0 step 6:- end
CPP
// reverse a string using shell script // reverse a string is in linux and unix #!/ bin / bash // reading a string // using via user input read - p "Enter string:" string // getting the length of given string
len
= $
{ #string
} // looping for reversing a string // initialize i=len-1 for reversing a string and run till i=0 // printing in the reverse order of the given string for ((i = $len - 1; i >= 0; i--))
do
// "${string:$i:1}"extract single character from string.
reverse = "$reverse${string:$i:1}" done
echo "$reverse"
|
Output:
skeegrofskeeg
Reverse a string in shell scripting using Commands
- rev command : It is used to reverse the lines in a file. This command can take standard input as well as shown below.
$ echo welcome | rev emoclew
- Note: The rev command is not present in all flavors of Unix.
- awk command : Using the substring function, can reverse a string:
$ echo welcome | awk '{ for(i = length; i!=0; i--) x = x substr($0, i, 1); }END {print x}' emoclew
- This logic is the common logic used in any programming language to reverse a string: Start from the last position of the string and keep printing a character till the first position is reached. We loop on the string starting from the last position and moving towards the beginning. The length command gives the length of the argument passed to it. With no argument, length gives the length of the current line which is $0. The substr command in awk extracts one character at a time and is appended to the resultant variable x which is printed at the end using the END label.
- sed command : Total 2 sed commands are used here.
$ echo welcome | sed 's/./&\n/g' | tac | sed -e :a -e 'N;s/\n//g;ta' emoclew
- To understand this command properly, break it up at every pipe and observe the output. The first sed reads a character(.) and appends a newline(\n) character behind every matched character(&). tac command reverses the contents of a file or the standard input. The second sed command now joins all the lines together. Note: The tac command is not present in all the Unix flavors.
- Perl solution : Using the inbuilt perl function reverse.
$ echo welcome | perl -ne 'chomp; print scalar reverse;' emoclew
- reverse function reverses all the elements present in a list. In scalar context as used here, it reverses a string as well. The chomp command is used to remove the newline character in the string.
.