Home > Blockchain >  How to split string to array with specific word in bash
How to split string to array with specific word in bash

Time:01-18

I have a string after I do a command:

[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)

Then I do IFS=", " read -r -a vertices <<< "$(gsql use graph ifgl ls | grep "Graph ifgl(" | cut -d "(" -f2 | cut -d ")" -f1)" to make the string splitted and append to array. But, what I want is to split it by delimiter ", " then append each word that contain ":v" to an array, its mean word that contain ":e" will excluded.

How to do it? without do a looping

CodePudding user response:

Like this, using grep

mapfile -t array < <(gsql ls | grep "Graph graph_name" | grep -oP '\b\w :v')

The regular expression matches as follows:

Node Explanation
\b the boundary between a word char (\w) and something that is not a word char
\w word characters (a-z, A-Z, 0-9, _) (1 or more times (matching the most amount possible))
:v ':v'

CodePudding user response:

This bash script should work:

declare arr as array variable
arr=()

# use ", " as delimiter to parse the input fed through process substituion
while read -r -d ', ' val || [[ -n $val ]]; do
   val="${val%)}"
   val="${val#*\(}"
   [[ $val == *:v ]] && arr =("$val")
done < <(gsql ls | grep "Graph graph_name")

# check array content
declare -p arr

Output:

declare -a arr='([0]="Vertice_1:v" [1]="Vertice_2:v" [2]="Vertice_3:v" [3]="Vertice_4:v")'

CodePudding user response:

Since there is a condition per element the logical way is to use a loop. There may be ways to do it, but here is a solution with a for loop:

#!/bin/bash
input="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"
input="${input//,/ }" #replace , with SPACE (bash array uses space as separator)
inputarray=($input)
outputarray=()
for item in "${inputarray[@]}"; do
  if [[ $item =~ ":v" ]]; then
    outputarray =($item) #append the item to the output array
  fi
done
echo "${outputarray[@]}"

will give output: Vertice_1:v Vertice_2:v Vertice_3:v Vertice_4:v

since the elements don't have space in them this works

  • Related