Reverse a String | Shell Programming
Last Updated :
18 Oct, 2024
In shell scripting, reversing a string can be done using various methods, such as rev, awk, sed, and Perl. Here, we provide examples of reversing a string using different approaches and commands in Unix/Linux systems. We are given a string and we have to use shell script to print it in the reverse order.
Syntax
The general syntax varies depending on the command used for reversing the string.
Using rev command:
echo "string" | rev
Using awk command:
echo "string" | awk '{ for(i = length; i!=0; i--) x = x substr($0, i, 1);} END {print x}'
Using sed and tac:
echo "string" | sed 's/./&\n/g' | tac | sed -e :a -e 'N;s/\n//g;ta'
Using perl:
echo "string" | perl -ne 'chomp; print scalar reverse;'
Key Methods for Reversing Strings
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
Method 1: Using rev Command
The rev command reverses the lines in a file or from standard input.
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.
Method 2: Using awk Command
Using awk to reverse a string by iterating over each character from the end and appending it.
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.
Method 3: Using sed and tac Commands
This method uses sed to append a newline after every character, tac to reverse the lines, and sed again to join them.
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.
Method 4: Using perl
The perl solution uses the built-in reverse function to reverse the string.
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.
Conclusion
Reversing a string in shell programming can be done using a variety of commands such as rev, awk, sed, or perl. Each method has its own use cases, with some commands being more readily available on certain systems.
Similar Reads
Reverse a string preserving space positions
Given a string s, the task is to reverse the given string while preserving the position of spaces.Examples: Input: "internship at geeks for geeks"Output: skeegrofsk ee gtapi hsn retniExplanation : Reversing the characters without spaces "skeegrofskeegtapihsnretni" and inserting space at original pla
7 min read
Reverse words in a string
Given a string str, your task is to reverse the order of the words in the given string. Note that str may contain leading or trailing dots(.) or multiple trailing dots(.) between two words. The returned string should only have a single dot(.) separating the words.Examples:Input: str = "i.like.this.p
11 min read
Print reverse string after removing vowels
Given a string s, print reverse of string and remove the characters from the reversed string where there are vowels in the original string. Examples: Input : geeksforgeeksOutput : segrfsegExplanation :Reversed string is skeegrofskeeg, removing characters from indexes 1, 2, 6, 9 & 10 (0 based ind
13 min read
Reverse vowels in a given string
Given a string s, reverse only the vowels in s while keeping the other characters in their original positions.Examples:Input: "geeksforgeeks"Output: "geeksforgeeks"Explanation: The vowels 'e', 'e', 'o', 'e', 'e' are reversed, resulting in "geeksforgeeks".Input: "helloworld"Output: "hollowerld"Explan
9 min read
How to reverse a String in Python
Reversing a string is a common task in Python, which can be done by several methods. In this article, we discuss different approaches to reversing a string. One of the simplest and most efficient ways is by using slicing. Letâs see how it works:Using string slicingThis slicing method is one of the s
4 min read
String Operators | Shell Script
Pre-Requisite: Conditional Statement in Shell Script There are many operators in Shell Script some of them are discussed based on string. Equal operator (=): This operator is used to check whether two strings are equal. Syntax:Operands1 = Operand2Example:Â php #!/bin/sh str1="GeeksforGeeks"; str2="ge
2 min read
Print reverse of a string using recursion
Given a string, the task is to print the given string in reverse order using recursion.Examples:Input: s = "Geeks for Geeks"Output: "skeeG rof skeeG"Explanation: After reversing the input string we get "skeeG rof skeeG". Input: s = "Reverse a string Using Recursion"Output: "noisruceR gnisU gnirts a
5 min read
Easiest Way to Reverse a String
Have you wondered which is the easiest way to reverse a string, Imagine you are giving a contest and an algorithm you have made requires reversing a string, you must be aware of the easiest way to reverse a string. What is a reversal of string:Reversing a string is the technique that reverses or cha
4 min read
Reverse a String using Stack
Given a string str, the task is to reverse it using stack. Example:Input: s = "GeeksQuiz"Output: ziuQskeeGInput: s = "abc"Output: cbaAlso read: Reverse a String â Complete Tutorial.As we all know, stacks work on the principle of first in, last out. After popping all the elements and placing them bac
3 min read
Perfect reversible string
You are given a string 'str', the task is to check the reverses of all possible substrings of 'str' are present in 'str' or not. Examples: Input : str = "ab" Output: "NO" // all substrings are "a","b","ab" but reverse // of "ab" is not present in str Input : str = "aba" Output: "YES" Input : str = "
6 min read