LoginSignup
4
2

More than 1 year has passed since last update.

Linux: 大文字小文字変換方法

Posted at

たまに必要となるのでメモ。

実施環境:
Linux
[testuser@testhost ~]$ uname -a
Linux testhost 4.18.0-147.8.1.el8_1.x86_64 #1 SMP Thu Apr 9 13:49:54 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
[testuser@testhost ~]$ echo $SHELL
/bin/bash

Linuxは基本的に、大文字/小文字を明確に区別します。
そのため、文字列の大文字/小文字を意図的に揃えたい場合がしばしば発生します。
それを実現する方法を4つ紹介します。

1. trコマンド

一番単純なのは、trコマンドを使用することです。
小文字a-zの組と大文字A-Zの組の変換の他、
大文字/小文字のセットを表す[:upper:]及び[:lower:]でも変換可能。

Linux
[testuser@testhost ~]$ echo "Hello World!"
Hello World!
[testuser@testhost ~]$ echo "Hello World!" | tr [a-z] [A-Z]
HELLO WORLD!
[testuser@testhost ~]$ echo "Hello World!" | tr [A-Z] [a-z]
hello world!
[testuser@testhost ~]$ echo "Hello World!" | tr [:lower:] [:upper:]
HELLO WORLD!
[testuser@testhost ~]$ echo "Hello World!" | tr [:upper:] [:lower:]
hello world!

2. sedコマンド

sedコマンドでも大文字/小文字変換が可能です。
文字列全体を表す.*を()で括って一纏めにして
後方参照\1で参照、参照した文字列を\Uまたは\Lで大文字/小文字にして
変換前の文字列全体と変換後の文字列全体を置き換えます。

Linux
[testuser@testhost ~]$ echo "Hello World!" | sed "s/\(.*\)/\U\1/"
HELLO WORLD!
[testuser@testhost ~]$ echo "Hello World!" | sed "s/\(.*\)/\L\1/"
hello world!

3. awkコマンド

awkコマンドでも変換できます。
awk内の関数であるtoupper/tolower関数に文字列全体を表す$0を与えて、
その結果を出力します。

Linux
[testuser@testhost ~]$ echo "Hello World!" | awk '{print toupper($0)}'
HELLO WORLD!
[testuser@testhost ~]$ echo "Hello World!" | sed '{print tolower($0)}'
hello world!

4. bash内の機能

bash4.0以降の場合は、変数に代入した値から変換することも可能です。
${変数名^^}で大文字に、${変数名,,}で小文字に変換できます。

Linux
[testuser@testhost ~]$ STR="Hello World!"
[testuser@testhost ~]$ echo $STR
Hello World!
[testuser@testhost ~]$ echo ${STR^^}
HELLO WORLD!
[testuser@testhost ~]$ echo ${STR,,}
hello world!
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2