Issue
How can I store whole line output from grep
as 1 variable, not for every string.
Example (I need just 3 variables, whole lines).
user@local:~/bin/kb$ grep -E '##.*bash.*file.*add' bash.kb
## bash, file, add string behind founded string
## bash, files, add string to begin
## bash, file, add comma to end of line except last line
user@local:~/bin/kb$
But for
example.
user@local:~/bin/kb$ for i in $(grep -E '##.*bash.*file.*add' bash.kb); do echo $i; done
##
bash,
file,
add
string
behind
founded
string
##
bash,
files,
add
string
to
begin
##
bash,
file,
add
comma
to
end
of
line
except
last
line
user@local:~/bin/kb$
I need this (only 3 variables as whole line).
1st variable $i[0] = '## bash, file, add string behind founded string'
2nd variable $i[1] = '## bash, files, add string to begin'
3rd variable $i[2] = '## bash, file, add comma to end of line except last line'
How can I do that?
Thanks.
Your issue is that
iterates over whitespace-delimited words in the command output. This is sometimes referred to as word splitting or more generally as split + glob.
You can read lines into an indexed array in bash using
mapfile
(or its synonym,readarray
). Becausemapfile
reads from standard input, replace the command substitution$( ... )
with a process substitution<( ... )
:You can retrieve the values using
"${var[0]}"
,"${var[1]}"
etc. (arrays are zero-based) or loop over them all usingNote the use of double quotes to prevent word-splitting within the array elements.
If you don't actually need variables at all, and simply want to loop over the lines of command output, then use a
while
loop in place of afor
loop: