テキスト行からタグを抽出する[閉じる]

テキスト行からタグを抽出する[閉じる]

bashスクリプトとgrep / awk / sedを使用して、単一の文字区切り文字を持つ既知のパターンと一致する行をどのように配列に分割できますtoken1;token2;token3;token4a[0] = token1a[3]=token4

答え1

修正するこの方法で配列を作成することは、IFSが空白ではなく単一文字である場合にのみ適しています。そしてデータ文字列には連続した区切り文字はありません。
この問題に対する解決策と同様の解決策については、ここに進んでください。UnixとLinuxの問題...(IFSのより深い理解のために読む価値があります。


IFS(内部フィールド区切り文字)bash(およびash、ksh、zshなどの他のPOSIXシェル)を使用します。

挿入されたスペースのみを許可するIFSを使用すると、外部呼び出しを回避できます。

# ==============
  A='token0:token1:token2.y   token2.z '
  echo normal. $A
# Save IFS; Change IFS to ":" 
  SFI=$IFS; IFS=:     ##### This is the important bit part 1a 
  set -f              ##### ... and part 1b: disable globbing
  echo changed $A
  B=($A)  ### this is now parsed at :  (not at the default IFS whitespace) 
  echo B...... $B
  echo B[0]... ${B[0]}
  echo B[1]... ${B[1]}
  echo B[2]... ${B[2]}
  echo B[@]... ${B[@]}
# Reset the original IFS
  IFS=$SFI             ##### Important bit part 2a
  set +f               ##### ... and part 2b
  echo normal. $A

# Output
normal. token0:token1:token2.y token2.z
changed token0 token1 token2.y   token2.z 
B...... token0
B[0]... token0
B[1]... token1
B[2]... token2.y   token2.z 
B[@]... token0 token1 token2.y   token2.z 
normal. token0:token1:token2.y token2.z

答え2

2つの主な方法があります。一つはIFSFred.bearがデモンストレーション。これは別のプロセスを必要としないという利点がありますが、入力にシェルに特別な意味を持つ文字が含まれている場合、正しく入力するのは難しい場合があります。別の方法は、テキスト処理ユーティリティを使用することです。フィールド分割はに組み込まれていますawk

input="token1;token2;token3;token4"
awk -vinput="$input" 'BEGIN {
    count = split(input, a, ";");
    print "first field: " a[1];
    print "second: field" a[2];
    print "number of fields: " count;
    exit;
}'

awkは、複数の入力を処理する場合に特に適しています。

command_producing_semicolon_separated_data |
awk -F ';' '{
    print "first field: " $1;
    print "second field: " $2;
    print "number of fields: " NF;
}'

答え3

$ str="token1;token2;token3;token4"
$ echo $str
token1;token2;token3;token4
$ echo $str | tr ';' ' '
token1 token2 token3 token4
$ arr=( $(echo $str | tr ';' ' ') ) # Populate the tokens into an array
$ echo ${arr[0]}  # Access items by index
token1
$ echo ${arr[2]}
token3
$ echo ${arr[1]}
token2
$ echo ${#arr[@]}  # Length of the array
4

関連情報