Search code examples
arraysbashcut

Get values from a bash output


UPDATE: this was answered much more simply, and turned out not to need grep at all. Wow, is my face red!

I’m pretty new to bash programming, so there’s probably an easy answer for this, but while my Googling has turned up lots of bash grep examples and lots of bash array examples, it hasn’t turned up anything I can figure out how to adapt to what I’m trying to do.

The basic idea is that I want to pull one bit out of each line of another program’s output, and put those into an array. Suppose this is the output:

_ filename1 2015-11-06
. filename2 2015-11-04
X filename3 2015-11-01
_ filename4 2015-10-22

Everything there is space-separated, not tab-separated.

What I want to do is get an array in bash that contains just the filenames, and nothing else. So the result of running it against the example woudl be a four-item array. I’ve managed to create arrays that contains all of the space-separated pieces in sequence (thus 12 items), and plenty of empty arrays, but can’t figure out how to get just the filenames.

I’m on an older version of bash that isn’t mine to upgrade (3.2.53(1)-release), so readarray is not available.

Thanks for any assistance!


Solution

  • This version uses regexp and deals with spaces in filename:

    arr = (command | $(sed -s "s/^.\s\(.\+\)\s[0-9\-]\+\$/\1/"))
    

    Example:

    a="_ filename1 2015-11-06                                   
    . filename2 2015-11-04
    X filename3 2015-11-01
    _ filen a m e4 2015-10-22"
    
    echo "$(echo $a | sed -s "s/^.\s\(.\+\)\s[0-9\-]\+\$/\1/")"
    

    Outputs:

    filename1
    filename2
    filename3
    filen a m e4