I have variable in bash:
$ users_="a1 .localhost a2 a3 .localhost a4"
I'd like to read into bash array all phrases startking with 'a'
and ending with '.localhost'
, which in this case will be:
"a1 .localhost"
"a3 .localhost"
The regex should be I think a[0-9]+\s\.localhost
or ^a[0-9]+\s\.localhost$
(I'm not sure). The a2
and a4
prases should be ommited.
So, how to achieve it?
What i was trying is:
$ $users_ | grep '^a[0-9]+\s\.localhost$'
But it throws me an error.
Thanks for replies. Mike.
Solution : You can use mapfile and a for loop to write the lines.
users_="a1 .localhost a2 a3 .localhost a4"
mapfile -t users_array < <(echo "$users_" | grep -Eo 'a[0-9]+\s\.localhost')
for user in "${users_array[@]}"; do
echo "$user"
done
Expected result : When you run the ./your_file.bash, you get:
a1 .localhost
a3 .localhost
Elements a2 and a4 are ignored because they do not correspond to the desired format.