Linux Shell Title Case

Making a script that transforms sentences to title case?

How about just wrapping it into a function in .bashrc or .bash_profile and source it from the current shell

TitleCaseConverter() {
sed 's/.*/\L&/; s/[a-z]*/\u&/g' <<<"$1"
}

or) if you want it pitch-perfect to avoid any sorts of trailing new lines from the input arguments do

printf "%s" "$1" | sed 's/.*/\L&/; s/[a-z]*/\u&/g'

Now you can source the file once from the command line to make the function available, do

source ~/.bash_profile

Now you can use it in the command line directly as

str="my text"
newstr="$(TitleCaseConverter "$str")"
printf "%s\n" "$newstr"
My Text

Also to your question,

How can I convert this to a script so I can just call something like the following from the terminal

Adding the function to one of the start-up files takes care of that, recommend adding it to .bash_profile more though.

TitleCaseConverter "this is stackoverflow"
This Is Stackoverflow


Update:

OP was trying to create a directory with the name returned from the function call, something like below

mkdir "$(TitleCaseConverter "this is stackoverflow")"

The key again here is to double-quote the command-substitution to avoid undergoing word-splitting by shell.

linux shell title case

a GNU sed one-liner

echo something-that-is-hyphenated | 
sed -e 's/-\([a-z]\)/\u\1/g' -e 's/^[a-z]/\u&/'

\u in the replacement string is documented in the sed manual.

How to convert fully qualified class name into title case using a bash script?

⚠️ Not tested!

# Converts to upper-case:
# first word-letter at start or following a period
$ sed -e 's/^.|\.\w+/\u&/g' input.txt > output.txt

This uses common regular expression matcher:

  • ^ start of line, followed by any single character . (i.e. the initial letter at start)
  • | as boolean OR
  • \. for the period, followed by \w+ for one or many word-characters (letters)

but also some specials like:

  • back-reference & (full match pattern), where following is applied to:
  • transformation from GNU extensions \u (uppercase the next character of match), that may not work on MacOS.

Use sed's GNU extensions on MacOS

On MacOS (BSD sed) you can use gsed which must be installed, e.g. using homebrew:

brew install gnu-sed

Inspired by: https://stackoverflow.com/a/4581564

Alternatively you may achieve same (regex-uppercase transformation) by using Perl: https://unix.stackexchange.com/a/615804

How To: Convert Text Following Title Case Rules in Bash

$ cat titles.txt
purple haze
Somebody To Love
fire on the mountain
THE SONG REMAINS THE SAME
Watch the NorthWind rise
eight miles high
just dropped in
strawberry letter 23

$ cat cap.awk
BEGIN { split("a the to at in on with and but or", w)
for (i in w) nocap[w[i]] }

function cap(word) {
return toupper(substr(word,1,1)) tolower(substr(word,2))
}

{
for (i=1; i<=NF; ++i) {
printf "%s%s", (i==1||i==NF||!(tolower($i) in nocap)?cap($i):tolower($i)),
(i==NF?"\n":" ")
}
}

$ awk -f cap.awk titles.txt
Purple Haze
Somebody to Love
Fire on the Mountain
The Song Remains the Same
Watch the Northwind Rise
Eight Miles High
Just Dropped In
Strawberry Letter 23

EDIT (as a one liner):

$ echo "the sun also rises" | awk 'BEGIN{split("a the to at in on with and but or",w); for(i in w)nocap[w[i]]}function cap(word){return toupper(substr(word,1,1)) tolower(substr(word,2))}{for(i=1;i<=NF;++i){printf "%s%s",(i==1||i==NF||!(tolower($i) in nocap)?cap($i):tolower($i)),(i==NF?"\n":" ")}}'
The Sun Also Rises

How to convert a string to lower case in Bash

The are various ways:

POSIX standard

tr

$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all

AWK

$ echo "$a" | awk '{print tolower($0)}'
hi all

Non-POSIX

You may run into portability issues with the following examples:

Bash 4.0

$ echo "${a,,}"
hi all

sed

$ echo "$a" | sed -e 's/\(.*\)/\L\1/'
hi all
# this also works:
$ sed -e 's/\(.*\)/\L\1/' <<< "$a"
hi all

Perl

$ echo "$a" | perl -ne 'print lc'
hi all

Bash

lc(){
case "$1" in
[A-Z])
n=$(printf "%d" "'$1")
n=$((n+32))
printf \\$(printf "%o" "$n")
;;
*)
printf "%s" "$1"
;;
esac
}
word="I Love Bash"
for((i=0;i<${#word};i++))
do
ch="${word:$i:1}"
lc "$ch"
done

Note: YMMV on this one. Doesn't work for me (GNU bash version 4.2.46 and 4.0.33 (and same behaviour 2.05b.0 but nocasematch is not implemented)) even with using shopt -u nocasematch;. Unsetting that nocasematch causes [[ "fooBaR" == "FOObar" ]] to match OK BUT inside case weirdly [b-z] are incorrectly matched by [A-Z]. Bash is confused by the double-negative ("unsetting nocasematch")! :-)

How to convert to title case a specific column

GNU sed:

sed -ri 's/;/&\r/3;:1;s/\r([^; ]+\s*)/\L\u\1\r/;t1;s/\r//' columns.csv

update:

sed -i 's/; */&\n/3;:1;s/\n\([^; ]\+ *\)/\L\u\1\n/;t1;s/\n//' columns.csv

Place anchor \r (\n) at the beginning of field 4. We edit the whole word and move the anchor to the beginning of the next one. Jump by label t1 :1 is carried out as long as there are matches for the pattern in the substitution command. Removing the anchor.

uppercase first character in a variable with bash

foo="$(tr '[:lower:]' '[:upper:]' <<< ${foo:0:1})${foo:1}"

Uppercasing First Letter of Words Using SED

This line should do it:

sed -e "s/\b\(.\)/\u\1/g"

Correct Bash and shell script variable capitalization

By convention, environment variables (PAGER, EDITOR, ...) and internal shell variables (SHELL, BASH_VERSION, ...) are capitalized. All other variable names should be lower case.

Remember that variable names are case-sensitive; this convention avoids accidentally overriding environmental and internal variables.

Keeping to this convention, you can rest assured that you don't need to know every environment variable used by UNIX tools or shells in order to avoid overwriting them. If it's your variable, lowercase it. If you export it, uppercase it.



Related Topics



Leave a reply



Submit