Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into two levels

Tags:

bash

I have the following string

my_str="A:Apple|B:Ball|C:Cat"

and I want to echo the following

A for Apple
B for Ball
C for Cat

The code I use is

IFS="|"
delimiter=':'
my_str="A:Apple|B:Ball|C:Cat"
for pair in ${my_str}; do
  #echo "${pair}"
  s=$pair$delimiter
  var1=${s%%"$delimiter"*}
  var2=${s#*"$delimiter"}
  echo "${var1} for ${var2}"
done

But the output I get is

A for Apple:
B for Ball:
C for Cat:

Could someone help me remove the extra delimiter appended at the end?

like image 755
Amber Avatar asked Jun 17 '26 16:06

Amber


2 Answers

bash's read provides an option (-d) for customizing the line delimiter, you can use it in conjunction with IFS.

while IFS=':' read -r -d '|' k v; do
    printf '%s for %s\n' "$k" "$v"
done <<< ${my_str%|}'|'
like image 171
oguz ismail Avatar answered Jun 20 '26 06:06

oguz ismail


1st solution: Could you please try following.

echo "$my_str" | awk -F'|' '{gsub(/:/," for ");for(i=1;i<=NF;i++){print $i}}'

2nd solution: Using gsub fair warning, written and tested with shown samples only.

echo "$my_str" | awk '{gsub(/:/," for ");gsub(/\|/,"\n")} 1'

Output will be as follows.

A for Apple
B for Ball
C for Cat
like image 26
RavinderSingh13 Avatar answered Jun 20 '26 07:06

RavinderSingh13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!