从一行文本中提取标记

Jas*_*Jas 5 grep bash sed awk text-processing

使用 bash 脚本和 grep/awk/sed,如何将匹配已知模式的行与单个字符分隔符拆分为数组,例如转换token1;token2;token3;token4a[0] = token1... a[3]=token4

Pet*_*r.O 7

更新请注意,仅当 IFS 是单个非空白字符并且数据字符串中没有多个连续分隔符时,才适合以这种方式制作数组。
有关解决此问题的方法和类似的解决方案,请转到此Unix 和 Linux 问题...(值得一读以深入了解 IFS。


使用 bash(和其他 POSIX shell,例如 ash、ksh、zsh)的IFS(内部字段分隔符)。

使用 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
Run Code Online (Sandbox Code Playgroud)


Bar*_*run 0

$ 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
Run Code Online (Sandbox Code Playgroud)