LoginSignup
0
2

More than 5 years have passed since last update.

Bashでsplitみたいな処理

Posted at

メモ書き。

引数で指定したファイルのレコードを1行づつデリミタで区切る処理。
(例はカンマ(,)区切)

読み込むファイル

test.txt
bokuha,hentai

シェル

split.sh
#!/bin/sh
filename=$1
IFS=','
while read line ; do
  set -- ${line}
  echo $1
  echo $2
done < ${filename}

実行結果

[xxx@xxx xxx]# ./split.sh test.txt
bokuha
hentai
[xxx@xxx xxx]#

説明(一応)

filename=$1
→引数1に指定したファイル名を変数に設定。

IFS=','
デリミタ変数IFSに','を設定。
IFSはBashのデリミタの環境変数。デフォルトだと"$'\n'$'\t' "(改行・タブ・半角スペース)が設定されている。

while read line ; do ~ done < ${filename}
ファイルを1行ずつ読み込み。
readコマンドはIFSの値で読んだ行を区切り変数に格納($1,$2,...)

補足

IFSはexportで定義しちゃうと(今回は関係ないけど)子プロセスに影響を与えちゃうので注意(用が済んだら戻す/必要なければシェル変数で)。

0
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
0
2