Home > Net >  Creating an array of Strings from Grep Command
Creating an array of Strings from Grep Command

Time:03-05

I'm pretty new to Linux and I've been trying some learning recently. One thing I'm struggling is Within a log file I would like to grep for all the unique IDs that exist and store them in an array.

The format of the ids are like so id=12345678,

I'm struggling though to get these in to an array. So far I've tried a range of things, the below however

a=($ (grep -HR1 `id=^[0-9]' logfile))
echo ${#a[@]}

but the echo count is always returned as 0. So it is clear the populating of the array is not working. Have explored other pages online, but nothing seems to have a clear explanation of what I am looking for exactly.

CodePudding user response:

Here is an example

my_array=()
while IFS= read -r line; do
    my_array =( "$line" )
done < <( ls )
echo ${#my_array[@]}
printf '%s\n' "${my_array[@]}"

It prints out 14 and then the names of the 14 files in the same folder. Just substitute your command instead of ls and you started.

CodePudding user response:

a=($(grep -Eow 'id=[0-9] ' logfile))
a=("${a[@]#id=}")

printf '%s\n' "${a[@]}"
  • It's safe to split an unquoted command substitution here, as we aren't printing pathname expansion characters (*?[]), or whitespace (other than the new lines which delimit the list).
  • If this were not the case, mapfile -t a <(grep ...) is a good alternative.
  • -E is extended regex (for )
  • -o prints only matching text
  • -w matches a whole word only
  • ${a[@]#id=} strips the id suffix from each array element
  • Related