store the command output in an array and print one by one

16,088

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.

Share:
16,088

Related videos on Youtube

Gilles 'SO- stop being evil'
Author by

Gilles 'SO- stop being evil'

Updated on September 18, 2022

Comments

  • Gilles 'SO- stop being evil'
    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
    Stéphane Chazelas almost 10 years
    I 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
    Stéphane Chazelas almost 10 years
    You should also disable globbing (set -f) as you don't want that part of the split+glob operator here.
  • Marek Zakrzewski
    Marek Zakrzewski almost 10 years
    @StéphaneChazelas array+=.. is indeed useless in this case since the stdin is not user input but it's a file. And yes delimiter is set to indicate NULs or \0 ending of the arguments passed to the array otherwise unexpected result can occur.
  • holasz
    holasz almost 10 years
    I'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!