Saurabh Arora
Saurabh Arora

Reputation: 80

Parse string using delimiter and pick up elements from 2nd index till the last in Shell / Bash

I have a string of following format:

a|b|c|d|e|f|g

I want to parse this string on delimiter '|' into array, then I want to iterate over the array from 2nd index, i.e. (c d e f g) and then I want to validate each of these array values individually.

Upvotes: 0

Views: 89

Answers (4)

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

echo "a|b|c|d|e|f|g" | awk -F\| '{for(i=2;i<=NF;i++) {print $i}}'

Using "|" as delimiter, print from 2nd field to the last field.

Upvotes: 1

pjh
pjh

Reputation: 8084

You can do this with pure Bash:

teststring='a|b|c|d|e|f|g'

IFS='|' read -d '' -a arr <<<"$teststring"

for (( idx=2 ; idx < ${#arr[*]} ; idx++ )) ; do
    echo "validate ${arr[idx]}"
done

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

To parse the string to array

Using sed

$ array= ( $(echo "a|b|c|d|e|f|g" | sed 's/|/ /g') )

Using tr

$ array=( $(echo "a|b|c|d|e|f|g" | tr '|' ' ') )

Any loop can help you iterate through the array

for example while loop will do

i=2
while [ $i -lt  ${#array[@]} ]
do 
echo ${array[$i]}
(( i=$i+1 ))
done

Will give an output as

c
d
e
f
g

Upvotes: 1

SMA
SMA

Reputation: 37023

Try awk:

echo "a|b|c|d|e|f|g" | awk -F'|' '{ if ($2 == "b") {print "Yo i found b" } else printf("i dont know <%s>", $2)}'

awk -F - With field seperator as "|"
if - $2 is second field am comparing with b, saying if i find b then print i found it else say i dont know b

Upvotes: 1

Related Questions