首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BASH将单行拆分成键、值对。例如A,B,C| 1,2,3到A,1 B,2 C,3

BASH将单行拆分成键、值对。例如A,B,C| 1,2,3到A,1 B,2 C,3
EN

Stack Overflow用户
提问于 2021-09-01 21:30:35
回答 3查看 103关注 0票数 0

我正在使用Tshark来拆分一些数据。问题是数据显示在单行上。为了使用它,我想把它拆分成键-值对。例如:

Tshark data- a,b,c,d,e,f,g | 1,2,3,4,5,6,7

我想要这样的格式- a,1 b,2 c,3 d,4 e,5 f,6 g,7

或者- [{a,1},{b,2}] etc..

谢谢!

EN

回答 3

Stack Overflow用户

发布于 2021-09-01 21:44:46

代码语言:javascript
复制
#!/usr/bin/env bash
#              ^^^^ - note bash; not zsh, not sh

processLine() {
  local data idx      # declare locals so we don't pollute global namespace
  local -a arr1 arr2  # declare local arrays separately
  data=$1             # assign our first positional argument to $data

  # no separator? bail out early
  [[ $data = *" | "* ]] || {
    echo "ERROR: Data not in expected form" >&2
    return 1
  }

  # break our two variables into two separate arrays
  IFS=, read -r -a arr1 <<<"${data%%' | '*}"
  IFS=, read -r -a arr2 <<<"${data#*' | '}"

  # iterate over those arrays by index/key to pair items up
  for idx in "${!arr1[@]}"; do
    printf '%s,%s ' "${arr1[$idx]}" "${arr2[$idx]}"
  done
  printf '\n'  # add a trailing newline
}

processLine 'a,b,c,d,e,f,g | 1,2,3,4,5,6,7'

https://ideone.com/6Ugk0H上运行此代码

票数 2
EN

Stack Overflow用户

发布于 2021-09-02 01:19:18

试试这个awk

代码语言:javascript
复制
$ echo "a,b,c,d,e,f,g | 1,2,3,4,5,6,7" | awk -F"[|, ]+" ' { for(i=1;i<=NF/2;i++) printf $i "," $(i+NF/2) " " } '
a,1 b,2 c,3 d,4 e,5 f,6 g,7
票数 0
EN

Stack Overflow用户

发布于 2021-09-02 07:31:59

由于您还标记了此zsh,因此仅使用其参数扩展的zsh解决方案:

代码语言:javascript
复制
#!/usr/bin/env zsh

data="a,b,c,d,e,f,g | 1,2,3,4,5,6,7"

# Split on pipe into an array
halves=( ${(s:|:)data} ) 
# Split the first array element on comma, first removing trailing spaces
first=( ${(s:,:)${halves[1]%% }} )
# Same with the second element and leading spaces
second=( ${(s:,:)${halves[2]## }} )

# Merge the two arrays by alternating elements, and print out two elements
# at a time so it looks like
# a,1 b,2 c,3 d,4 e,5 f,6 g,7
printf "%s,%s " ${first:^second}
printf "\n"

# Or to render as
# [{a,1},{b,2},{c,3},{d,4},{e,5},{f,6},{g,7}]
pairs=$(printf "{%s,%s}\001" ${first:^second})
printf "[%s]\n" "${(j:,:)${(ps:\001:)pairs}}"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69020767

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档