WillBroadbent
WillBroadbent

Reputation: 1034

Using awk to set first character to lowercase UNIX

I've written the following bash script that utilizes awk, the aim is to set the first character to lower case. The script works mostly fine, however I'm adding an extra space when I concat the two values. Any ideas how to remove this errant space?

Script:

#!/bin/bash

foo="MyCamelCaseValue" 
awk '{s=tolower(substr($1,1,1))}{g=substr($1,2,length($1))}{print s,g}' <<<$foo

Output:

m yCamelCaseValue

edit:

Please see discussion from Bobdylan and RavinderSingh13 on accepted answer as it highlights issues with default MacOs bash version.

bash --version GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin19) Copyright (C) 2007 Free Software Foundation, Inc.

Upvotes: 0

Views: 1227

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133508

You were close and good try, you need not get length of line here, substr is intelligent enough to get the rest of the length of you mention a character position and don't give till where it should print(length value). Could you please try following.

(Usually these kind of problems could be solved by bash itself but when OP tried bash solution provided by @bob dylan its having issues because of OLD version of BASH, hence I am undeleting this one which is working for OP)

echo "$foo" | awk '{print tolower(substr($0,1,1)) substr($0,2)}' Input_file

Explanation:

  • Use substr function of awk to get sub-strings in current line.
  • Then grab the very first letter by substr($0,1,1) and wrap it inside tolower to make it in small case.
  • Now print rest of the line(since first character is already being captures by previous substr) by doing `substr($0,2) this will print from 2nd character to last of line.


EDIT by @bob dylan:

https://www.shell-tips.com/mac/upgrade-bash/

MacOS comes with an older version of bash. However if you're on 4+ you should be able to use the native bash function to translate the first character from upper to lower:

$ bash --version
GNU bash, version 4.4.19(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
 
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
$ cat foo.sh
#!/bin/bash
foo="MyCamelCaseValue"
echo "${foo,}"
$ bash foo.sh
myCamelCaseValue

Further examples for the whole string, to lower, to upper etc.

$ echo $foo
myCamelCaseValue
echo "${foo,}"
myCamelCaseValue
$ echo "${foo,,}"
mycamelcasevalue
$ echo "${foo^}"
MyCamelCaseValue
$ echo "${foo^^}"
MYCAMELCASEVALUE

Upvotes: 6

Related Questions