如何在Bash中拆分字符串并提取含:v的元素到数组(无循环)
提取图顶点元素到数组的无循环实现
问题场景
执行gsql ls | grep "Graph graph_name"后得到输出:
[username@hostname ~/script]$ gsql ls | grep "Graph graph_name" - Graph graph_name(Vertice_1:v, Vertice_2:v, Vertice_3:v, Vertice_4:v, Edge_1:e, Edge_2:e, Edge_3:e, Edge_4:e, Edge_5:e)
当前使用的命令会将带:e的边元素也存入数组,不符合需求:
IFS=", " read -r -a vertices <<< "$(gsql use graph ifgl ls | grep "Graph ifgl(" | cut -d "(" -f2 | cut -d ")" -f1)"
需求:按", "拆分后,仅将含:v的顶点元素存入数组,且不使用循环。
解决命令
IFS=", " read -r -a vertices <<< "$(gsql use graph ifgl ls | grep "Graph ifgl(" | cut -d "(" -f2 | cut -d ")" -f1 | tr ', ' '\n' | grep ":v" | tr '\n' ', ' | sed 's/, $//')"
命令分步解释
tr ', ' '\n':将", "分隔符替换为换行,让每个元素单独占一行,方便后续过滤grep ":v":仅保留包含:v的顶点元素,过滤掉带:e的边元素tr '\n' ', ':将换行符重新替换回", ",恢复原分隔格式,适配read的数组拆分规则sed 's/, $//':去除最后一个元素末尾多余的", ",避免数组出现空元素
验证结果
执行以下命令查看数组内容:
printf "%s\n" "${vertices[@]}"
输出将仅包含顶点元素:
Vertice_1:v Vertice_2:v Vertice_3:v Vertice_4:v
内容的提问来源于stack exchange,提问作者Yudha Restu
相关产品推荐
相关产品推荐

