0

I want to read a string and split it into words and check if there is a space after each word. I tried the below logic however how can I know if there's a space after DATABASE_URL.

#! /bin/bash

string="/dir1/dir2/dir3/dir4/dir/5/data.sql;DATABASE_URL ;5;value;/dir1/dir2/dir3/dir4/dir5/output.sql"

IFS=';'

read -ra arr <<< "$string"

# Print each value of the array by using the loop
for val in "${arr[@]}";
do
  printf "name = $val\n"
done

Output of above script:

name = /dir1/dir2/dir3/dir4/dir/5/data.sql
name = DATABASE_URL
name = 5
name = value
name = /dir1/dir2/dir3/dir4/dir5/output.sql

Help here would be much appreciated.

1
  • What do you want to do in script when there is a space present? Commented Feb 17, 2022 at 16:58

1 Answer 1

2

You could use grep to check if word ends with a space, like so: grep " $".

#! /bin/bash

string="/dir1/dir2/dir3/dir4/dir/5/data.sql;DATABASE_URL ;5;value;/dir1/dir2/dir3/dir4/dir5/output.sql"

IFS=';'

read -ra arr <<< "$string"

# Print each value of the array by using the loop
for val in "${arr[@]}";
do
  echo $val | grep -q " $" && echo -ne "Contains space at the end: "
  printf "name = $val\n"
done

Output:

amvara@development:/tmp$ ./test.sh
name = /dir1/dir2/dir3/dir4/dir/5/data.sql
Contains space at the end: name = DATABASE_URL
name = 5
name = value
name = /dir1/dir2/dir3/dir4/dir5/output.sql
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.