Ubuntu – Add particular strings to an array sed/awk/grep

bashcommand linescriptstext processing

I have this

ciscoFlashCopyStatus OBJECT-TYPE
        SYNTAX  INTEGER
                {  
                copyOperationPending(0),
                copyInProgress(1),
                copyOperationSuccess (2),
                copyInvalidOperation (3),
                copyInvalidProtocol (4),
                copyInvalidSourceName (5),
                copyInvalidDestName (6),
                copyInvalidServerAddress (7),
                copyDeviceBusy (8),
                copyDeviceOpenError (9),
                copyDeviceError (10),
                copyDeviceNotProgrammable (11),
                copyDeviceFull (12),
                copyFileOpenError (13),
                copyFileTransferError(14),
                copyFileChecksumError(15),
                copyNoMemory (16),
                copyUnknownFailure(17),
                copyInvalidSignature(18)
                }
        MAX-ACCESS      read-only
        STATUS  current     

What I want to do

Some command to copy each name of VARIABLE into a array named var

So example of output

echo "${var[0]}
copyOperationPending

echo "${var[1]}
copyInProgress

echo "${var[2]}
copyOperationSuccess

and so on..

Any ideas how can I achieve this?

NOTE This is kind of a similar question I had asked earlier how ever somethings have changed and I can no longer use the same solution provided in the old question.

Best Answer

Using grep:

mapfile -t var < <(grep -Po '^\s+\K[^ ]+(?= ?\(\d+\),?$)' file.txt)
  • grep -P will use PCRE (Perl Compatible Regular Expression)

  • grep -o will print the matched portion of the line

  • ^\s+\K will match the lines starting with whitespaces and \K will discard the match

  • [^ ]+ will match our desired portion

  • (?= *\(\d+\)) is the zero width positive look ahead pattern ensuring zero or one space followed by (, one or more digits, ) and zero or one , at the end after our desired match

  • mapfile is a shell built-in, used to create array.

    $ mapfile -t var < <(grep -Po '^\s+\K[^ ]+(?= ?\(\d+\),?$)' file.txt)
    
    $ echo "${var[0]}"
    copyOperationPending
    
    $ echo "${var[1]}"
    copyInProgress
    
    $ echo "${#var[@]}"
    19
    
Related Question