Quantcast
Channel: Bashタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 2722

bash上で"1_2_3_4_5_6_7_8_9_0"の文字列をアンダーバー"_"を基準に分割する

$
0
0

"1_2_3_4_5_6_7_8_9_0"の文字列をアンダーバー"_"を基準に分割するには、
cutを使えばよい

$ echo 1_2_3_4_5_6_7_8_9_0 | cut -d "_" -f 1
1

全てを分割するには1つ1つ入力してもよいが、

(例)全てのアンダーバー"_"を1つ1つ分割する場合
echo 1_2_3_4_5_6_7_8_9_0 | cut -d "_" -f 1
echo 1_2_3_4_5_6_7_8_9_0 | cut -d "_" -f 2
echo 1_2_3_4_5_6_7_8_9_0 | cut -d "_" -f 3
echo 1_2_3_4_5_6_7_8_9_0 | cut -d "_" -f 4
echo 1_2_3_4_5_6_7_8_9_0 | cut -d "_" -f 5
echo 1_2_3_4_5_6_7_8_9_0 | cut -d "_" -f 6
echo 1_2_3_4_5_6_7_8_9_0 | cut -d "_" -f 7
echo 1_2_3_4_5_6_7_8_9_0 | cut -d "_" -f 8
echo 1_2_3_4_5_6_7_8_9_0 | cut -d "_" -f 9
echo 1_2_3_4_5_6_7_8_9_0 | cut -d "_" -f 10

以下のようにスクリプト化してもよい

test.sh
#!/bin/bash -x  SRC_STR="1_2_3_4_5_6_7_8_9_0"TARGET_STR=_
LIST=()RET=`echo${SRC_STR} | grep-o${TARGET_STR} | wc-l`for i in`seq 0 ${RET}`do# 分割した値を順番に配列へ格納するField=`expr${i} + 1`
    LIST[${i}]=`echo${SRC_STR} | cut-d"$TARGET_STR"-f${Field}`done# ---check                                                                                                                                                                                        echo"Check Result"echo${LIST[@]}for i in`seq 0 ${RET}`do
    echo${LIST[${i}]}done
$ bash test.sh
Check Result
1 2 3 4 5 6 7 8 9 0
1
2
3
4
5
6
7
8
9
0

参考

【 cut 】コマンド――行から固定長またはフィールド単位で切り出す


Viewing all articles
Browse latest Browse all 2722

Trending Articles