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?

#!/bin/ksh
 
typeset -i exists
str="ag-sd"
 
new_str=$str
 
exists=`print $new_str | grep "\-" | wc -l`
if [[ $exists -eq 1 ]]
then
   str=`print $new_str | sed 's/\-/\_/g'`
fi
 
exists=`print $new_str | grep "\_" | wc -l`
if [[ $exists -eq 1 ]]
then
   str=`print $new_str | sed 's/\_/\-/g'`
fi
 
print "Old string $new_str"
print "New string $str"

Hi.

This looks like it does what you wish:

$ cat z8; tr '_-' '-_' < z8
abc-def_hij-klm_nop-qrs_tuv-wxy_z
abc_def-hij_klm-nop_qrs-tuv_wxy-z

and

$ echo "$s" ; echo "$s" | tr '_-' '-_'
abc-def_hij-klm_nop-qrs_tuv-wxy_z
abc_def-hij_klm-nop_qrs-tuv_wxy-z

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

1 Like

In sed you can use the y command

str='abc-def_hij-klm_nop-qrs_tuv-wxy_z'
newstr=`printf "%s\n" "$str" | sed 'y/_-/-_/'`
printf "%s\n" "$str" "$newstr"

With awk:

$ echo a_b-cc_dd_ee-ff | awk '{for(i=1; i<=NF; i++) gsub(OFS,FS,$i)}1'  FS=- OFS=_
a-b_cc-dd-ee_ff

--
ksh93:

$ echo "$var"
a_b-cc_dd_ee-ff
$ var2=${var//-/+} var2=${var2//_/-} var2=${var2//+/_}
$ echo "$var2"
a-b_cc-dd-ee_ff