Reputation: 418
I want to exchange the position of two string like 1A to A1
, 2B to B2
Is that possible in bash?
Now I'm doing it in a stupid way
case "$Zone" in
1A)
Zone="A1"
;;
2A)
Zone="A2"
;;
3A)
Zone="A3"
;;
4A)
Zone="A4"
;;
1B)
Zone="B1"
;;
2B)
Zone="B2"
;;
3B)
Zone="B3"
;;
4B)
Zone="B4"
;;
E)
Zone="E"
;;
esac
Is there any way smarter?
Upvotes: 1
Views: 97
Reputation: 1
Use the substring expansion to obtain the second and first characters of the string:
Zone=${Zone:1:1}${Zone:0:1}
Upvotes: 0
Reputation: 2653
If reverse a string works then give it a try
x=$(echo $zone | rev)
Hope it helps:)
Upvotes: 2
Reputation: 195059
your requirement is not clear, what are the possibilities of input? if only number + A or B
pattern is valid, and needs to be processed?
I assume you need that validation, and this one-liner does that job:
awk -v FS='' '/^[1-5][A-L]$/{$0=$2""$1}7'
some examples:
kent$ echo "1A
2A
3B
3X
E
foo"|awk -v FS='' '/^[1-5][A-L]$/{$0=$2""$1}7'
A1
A2
B3
3X
E
foo
you see that only if
2
[1-5]
A-L
it would be get reversed, otherwise, it keeps untouched.
Upvotes: 3
Reputation: 289725
If you happen to only have strings with 1 or 2 characters, you can reverse them. And oh, there is the rev
command in UNIX:
zone=$(echo "$zone" | rev)
or even shorter
zone=$(rev <<< "$zone")
See examples:
$ zone="E"
$ rev <<< "$zone"
E
$ zone="A1"
$ rev <<< "$zone"
1A
From man rev
:
rev — reverse lines of a file or files
Upvotes: 3