Unix/Linux Go Back    

Shell Programming and Scripting BSD, Linux, and UNIX shell scripting — Post awk, bash, csh, ksh, perl, php, python, sed, sh, shell scripts, and other shell scripting languages questions here.

Swap two characters in a string

Shell Programming and Scripting

Thread Tools Search this Thread Display Modes
Old Unix and Linux 1 Week Ago
Soham Soham is offline
Registered User
Join Date: Sep 2007
Last Activity: 24 July 2017, 4:02 PM EDT
Location: UNIX
Posts: 53
Thanks: 16
Thanked 1 Time in 1 Post
Swap two characters in a string

I want to swap hyphen (-) and underscore (_) in a string. In fact only one will be present. So if it is hyphen I want to make it underscore and if it is underscore I want to make it hyphen.

I can write a long code like below. Is there any easy way?

typeset -i exists
exists=`print $new_str | grep "\-" | wc -l`
if [[ $exists -eq 1 ]]
   str=`print $new_str | sed 's/\-/\_/g'`
exists=`print $new_str | grep "\_" | wc -l`
if [[ $exists -eq 1 ]]
   str=`print $new_str | sed 's/\_/\-/g'`
print "Old string $new_str"
print "New string $str"

Sponsored Links
Old Unix and Linux 1 Week Ago
drl's Unix or Linux Image
drl drl is offline Forum Advisor  
Registered Voter
Join Date: Apr 2007
Last Activity: 25 July 2017, 12:54 PM EDT
Location: Saint Paul, MN USA / BSD, CentOS, Debian, OS X, Solaris
Posts: 2,138
Thanks: 210
Thanked 392 Times in 340 Posts

This looks like it does what you wish:

$ cat z8; tr '_-' '-_' < z8


$ echo "$s" ; echo "$s" | tr '_-' '-_'

For a system like:

OS, ker|rel, machine: Linux, 3.16.0-4-amd64, x86_64
Distribution        : Debian 8.8 (jessie) 
tr (GNU coreutils) 8.23

Best wishes ... cheers, drl
The Following User Says Thank You to drl For This Useful Post:
Soham (1 Week Ago)
Sponsored Links

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Linux More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
remove characters from string based on occurrence of a string victor369 Shell Programming and Scripting 5 02-03-2011 08:37 PM
Swap different size string rupeshkp728 Programming 2 06-29-2010 08:17 AM
Swap device file and swap sapce lamoul HP-UX 6 03-04-2010 08:14 AM
get certain characters in a string jimmy_y Shell Programming and Scripting 4 01-28-2010 07:44 PM
Add string after another string with special characters heliode Shell Programming and Scripting 2 03-21-2008 08:06 AM

All times are GMT -4. The time now is 08:42 PM.