我正在使用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..
谢谢!
发布于 2021-09-01 21:44:46
#!/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上运行此代码
发布于 2021-09-02 01:19:18
试试这个awk
$ 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发布于 2021-09-02 07:31:59
由于您还标记了此zsh,因此仅使用其参数扩展的zsh解决方案:
#!/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}}"https://stackoverflow.com/questions/69020767
复制相似问题