store the command output in an array and print one by one
Solution 1
To strat with, using cat, grep and awk
is usually wrong. You now have
cat /etc/httpd/conf/httpd.conf | grep ^LogLevel | awk -F\" '{print $(NF)}'
To read the lines in an array you can use read
while read -rd '' -a array
do array+=("$REPLY")
done < <(awk -F\" '/^LogFormat/{ print $(NF)}' httpd.conf)
printf '%s\n' "${array[0]}"
Solution 2
Using arrays or loops in shells is often signs of bad coding practice. A shell is a tool to run other commands. awk
is the typical command to do complicated tasks with fields in text records. You want to call awk
once for your task, not a loop where you're going to run hundreds of commands.
If you want to print an index and last field name for the lines starting with ^LogFormat
, it's:
awk '/^LogFormat/{print n++, $NF}' httpd.conf
No need for cat
(which is for concatenating), nor grep
(awk
is a superset of grep
) or a shell array or a shell loop.
Related videos on Youtube
![Gilles 'SO- stop being evil'](https://i.stack.imgur.com/cFyP6.jpg?s=256&g=1)
Gilles 'SO- stop being evil'
Updated on September 18, 2022Comments
-
Gilles 'SO- stop being evil' almost 2 years
This is my command:
cat httpd.conf | grep ^LogFormat | awk -F\" '{print $(NF)}'
Output of this:
commonsess common
or can be any number of values, I need to store these values in an array and print one by one...using their index number.
-
Stéphane Chazelas almost 10 yearsI meant that your
array+=("$REPLY")
for instance doesn't make much sense. Where's that REPLY coming from? Why read blank delimited fields of NUL delimited records? (and there's definitely nothing personal against you :-)) -
Stéphane Chazelas almost 10 yearsYou should also disable globbing (
set -f
) as you don't want that part of the split+glob operator here. -
Marek Zakrzewski almost 10 years@StéphaneChazelas
array+=..
is indeed useless in this case since thestdin
is not user input but it's a file. And yes delimiter is set to indicateNULs
or\0
ending of the arguments passed to the array otherwise unexpected result can occur. -
holasz almost 10 yearsI'm with Stephane here. The
array+=
seems not suited in this case. I've never seen it's use earlier though.. but it seems quite useful!