0

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.

2
  • 2
    Is that a backtick at the start of id=, or an artifact of the post? Commented Mar 4, 2022 at 15:33
  • Please edit your question to provide a minimal reproducible example with concise, testable sample input and expected output so we can best help you. Commented Mar 5, 2022 at 14:07

3 Answers 3

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.
  • -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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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[@]}"

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.