'Creating an array of Strings from Grep Command
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.
Solution 1:[1]
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. -Eis extended regex (for+)-oprints only matching text-wmatches a whole word only${a[@]#id=}strips the id suffix from each array element
Solution 2:[2]
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.
Solution 3:[3]
Suggesting readarray command to make sure it array reads full lines.
readarray -t my_array < <(grep -HR1 'id=^[0-9]' logfile)
printf "%s\n" "${my_array[@]}"
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 | dan |
| Solution 2 | |
| Solution 3 |
