2

I am trying to get into UNIX. I want to replace and -, ?, :, /, & to become %5f, %3f %3a, %2f, %26, %20 (these are the hexadecimal digits corresponding to the ASCII code).

I am also trying to make any lower case characters become upper case and vice versa, e.g. the rock to become THE ROCK and THE ROCK to become the rock.

I am trying to do this all using standard UNIX utilities commands using a script, ideally all on one line.

So far I have got

tr A-Z a-z

but not sure how to make the ? and the other ones spit out the corresponding hex #s.

Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71
  • 1
    The hexadecimal conversion you're talking about is [url encoding](http://en.wikipedia.org/wiki/Percent-encoding) and for that you should check [urlencode-from-a-bash-script](http://stackoverflow.com/questions/296536/urlencode-from-a-bash-script) for several ideas. – n0741337 Apr 23 '14 at 06:34

1 Answers1

1

I want to make upper case to lower case and vise versa. like Hey TherE becomes hEY tHERe.

tr can do that:

$ echo Hey TherE | tr '[a-zA-Z]' '[A-Za-z]'
hEY tHERe

tr does translations and, in the above, translates lower case to upper case and vice versa.

As for replacing some characters with there hex value, here is a brute force method using sed:

$ echo "and-or?" | sed 's/-/%2d/g; s/?/%3f/g; s/:/%3a/g; s|/|%2f|g; s/&/%26/g; s/ /%20/g'
and%2dor%3f
John1024
  • 109,961
  • 14
  • 137
  • 171
  • woahh!!! what does the and or do? and shouldnt there be spaces between 'and5' and 'for'? – user3563184 Apr 23 '14 at 06:41
  • @user3563184 The string `and-or?` was just an example of input that contained two of your special characters: `-` and `?`. If you want `and-or?` to be converted to something else, let me know. – John1024 Apr 23 '14 at 06:45
  • I think im confused of what is going on. If I actually run that what will happen? I got a mismatched error. I guess im not sure what and-or actually is – user3563184 Apr 23 '14 at 06:48
  • @user3563184 The `$` is the command prompt. Your prompt may be longer but they usually end with `$`. `echo "and-or?"` creates sample input. Replace the string in quotes with whatever you want. The `sed...` part does the conversion. After running the command on the first line, the second line should appear as the output. (Let me know if I missed the point of your question.) – John1024 Apr 23 '14 at 06:52
  • Oh Sorry your right thank you so much. your awesome I just read it 100 times and got it lol – user3563184 Apr 25 '14 at 22:21
  • ok so I want to make upper case to lower case and vise versa. like Hey TherE becomes hEY tHERe. SO I found out that tr A-Z a-z makes it uppercase to lower case. Any thoughts on that? – user3563184 Apr 25 '14 at 22:24
  • @user3563184 I added code for switching cases to the answer. – John1024 Apr 26 '14 at 09:08
  • I see thank you.What is the and%2dor%3f for? – user3563184 Apr 26 '14 at 14:11