Easiest way to use string in bash 3.2?

For example: var=dogand the echo $varconclusion is a dog . Use $varExpected Result Dog .

I tried several methods, but did not get the expected result. Some attempts:

echo $var | sed "s/[a-z]\&[:upper:]//"  #dog
echo $var | sed "s/([a-z])/[:upper:]/"  #dog
+4
source share
4 answers

You can use Python if this is an option:

After input from different people (thanks to everyone), this seems like a good working solution that matches OP requests for only the first letter suggested by @ PM2Ring:

The best proposed solution for the first character only

bash-3.2$ var="it an öyster life"
bash-3.2$ python -c "import sys;print sys.argv[1].decode('utf8').capitalize()" "$var"
It an öyster life

The following solutions try to make up for all the first characters of words in a string:

:

bash-3.2$ python -c "print raw_input().decode('utf-8').title()" <<<"it an öyster life" 
It An Öyster Life

:

bash-3.2$ var='dog is dog'
bash-3.2$ python -c "print raw_input().decode('utf-8').title()" <<<"$var"
Dog Is Dog

( ), , Python OSX 2.7.

1: ( @john1024 @dev-null)

.

,

var="it a dog life"
bash-3.2$ python -c "print '$var'.title()"
It A Dog Life

, : var="hello ''' world"

2: ( @mklement0)

Unicode

bash-3.2$ var='öyster'
bash-3.2$ python -c "print '$var'.title()"
öYster

, , ascii, title , Python2.

Unicode:

bash-3.2$ var='öyster'
python -c "print '$var'.decode('utf-8').title()" 
Öyster

, , , , :

python -c "print raw_input().decode('utf-8').title()" <<<"it an öyster life" 
+4

TL;DR:

  • OS X Unicode -, ASCII,

    • . tr .
  • GNU Unicode (Linux: ; OS X: Homebrew):

    • sed 's/^./\u&/' <<<'dog' # -> 'Dog'
      • OS X: brew install gnu-sed gsed sed
    • awk : . dev-null answer
      • OS X: brew install gawk gawk awk.
  • -, Unicode:

  • Bash 4+ Unicode, OS X Homebrew:

    • echo "${var^}"

Try

var='dog'
echo "$(tr '[:lower:]' '[:upper:]' <<<"${var:0:1}")${var:1}" # -> 'Dog'
  • tr '[:lower:]' '[:upper:]' <<<"${var:0:1}" char $var (${var:0:1}) tr .

  • ${var:1} char $var.

, Unicode-aware [1] OS X awk Python 2.x : @idjaw Python 2.x .decode('utf-8') , (tr , awk python).

[1] BSD tr, OS X. GNU tr, , , ASCII, - . .


sed:

OS X (BSD) sed, .

GNU sed, Homebrew -

sed 's/^./\u&/' <<<'dog' # -> 'Dog'

\u GNU Sed . , OS X Sed.

[:upper:] , , .
- tr, [:upper:] [:lower:] , .


Bash 4+:

var='dog'; echo "${var^}"
+6
var="hello world"
echo "$var" | awk '{print toupper(substr($0, 1, 1)) substr($0, 2)}' # Hello world

:

var="hello world"
echo "$var" | awk 'BEGIN{RS = " "};{printf("%s ", toupper(substr($0, 1, 1)) substr($0, 2))}' # Hello World
+3

, perl:

$ perl -lne 'use open qw(:std :utf8); print ucfirst' <<< 'dog'
Dog
$ perl -lne 'use open qw(:std :utf8); print ucfirst' <<< 'élan'
Élan

:

$ perl -C -lne 'print ucfirst' <<< 'élan'
Élan
+2

Source: https://habr.com/ru/post/1613061/


All Articles