この記事では、bash スクリプトで文字列を分割する方法について説明します。
単一の文字列を複数の文字列に分割することを文字列分割と呼びます。多くのプログラミング言語には文字列分割を実行するための組み込み関数がありますが、bash にはそれを行うための組み込み関数がありません。 bash で文字列の分割を実行するにはさまざまな方法があります。すべてのメソッドを例を挙げて 1 つずつ見てみましょう。
方法 1: IFS 変数を使用する
$IFS(Internal Field Separator) は特別なシェル変数です。これは区切り文字 (文字列を分割する基準となる 1 つ以上の文字のシーケンス) を割り当てるために使用されます。 「 」、「 」、「-」などの任意の値または文字を区切り文字として使用できます。値を $IFS 変数に割り当てた後、文字列値を読み取る必要があります。 「-r」および「-a」オプションを使用して文字列を読み取ることができます。
- 「-r」: エスケープ文字ではなくバックスラッシュ () を文字として読み取ります。
- 「-a」: 分割された単語を、-a オプションの後に宣言された配列変数に格納するために使用されます。
例 1: 文字列をスペースで分割する
コード:
#!/bin/bash # String text='Welcome to techcodeview.com' # Set space as the delimiter IFS=' ' # Read the split words into an array # based on space delimiter read -ra newarr <<< '$text' # Print each value of the array by using # the loop for val in '${newarr[@]}'; do echo '$val' done> 出力:
Welcome to techcodeview.com>
例 2: 文字列を記号で分割する
Pythonプログラミングの演算子
@記号を使用して文字列を分割します。
コード:
#!/bin/bash #String text='Welcome@[email protected]@!!' # Set @ as the delimiter IFS='@' # Read the split words into an array # based on space delimiter read -ra newarr <<< '$text' # Print each value of the array by # using the loop for val in '${newarr[@]}'; do echo '$val' done>
出力:
Welcome to techcodeview.com !!>
方法 2: IFS 変数を使用しない
この方法では、readarray コマンドに -d オプションを指定して文字列データを分割します。 「-d」: このオプションは、区切り文字を定義する IFS 変数として機能します。
例 1: 文字列をスペースで分割する
コード:
#!/bin/bash # Read the main string text='Welcome to techcodeview.com' # Split the string by space readarray -d ' ' -t strarr <<< '$text' # Print each value of the array by # using loop for (( n=0; n < ${#strarr[*]}; n++)) do echo '${strarr[n]}' done> 次に、スクリプトがどのように動作するかを見てみましょう。
- スクリプトは次の値を設定します。
text>techcodeview.com へようこそ。 - の
readarray>コマンドは、スペースを区切り文字として使用して文字列を配列に分割し、結果として配列が得られます。strarr>次の要素が含まれています: techcodeview.com へようこそ。 - for ループは、
strarr>配列。 - 各要素を 1 つずつ別々の行に出力します。
出力:
Welcome to techcodeview.com>
例 2: を使用して分割する ある コロンとして ある デリミタ
コード:
#!/bin/bash # Read the main string text='Welcome:to:techcodeview.com' # Split the string based on the delimiter, ':' readarray -d : -t strarr <<< '$text' # Print each value of the array by using # loop for (( n=0; n < ${#strarr[*]}; n++)) do echo '${strarr[n]}' done> 出力:
Welcome to techcodeview.com>
方法 3: 複数文字の区切り文字を使用して文字列を分割する
このメソッドでは、文字列データを格納するために変数が使用され、複数文字の区切り文字データを格納するために別の変数が使用されます。分割された文字列を格納する配列変数も宣言されています。
Javaサーバーページ
コード:
# Define the string to split text='HelloRomy HelloPushkar HelloNikhil HelloRinkle' # store multi-character delimiter delimiter='Hello' # Concatenate the delimiter with the # main string string=$text$delimiter # Split the text based on the delimiter newarray=() while [[ $string ]]; do newarray+=( '${string%%'$delimiter'*}' ) string=${string#*'$delimiter'} done # Print the words after the split for value in ${newarray[@]} do echo '$value ' done> 出力:
Romy Pushkar Nikhil Rinkle>