'Check for space in string in shell script
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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arslan Sohail Bano |
