Skip to main content
fixed the case of lines containing more commas, and while I'm at it made the script more robust in case the number isn't followed by a comma
Source Link
Gilles 'SO- stop being evil'
  • 865.4k
  • 205
  • 1.8k
  • 2.3k

Use parameter expansion:

#! /bin/bash

strings=('Job with id 0 ended with status COMPLETED, return code 16, in 1 minute 12 seconds'
         'Job with id 0 COMPLETED with return code 255'
        )

for string in "${strings[@]}" ; do
    code=${string#*return code }
    code=${code%,*code%%[!0-9]*}
    echo $code
done

# removes pattern from the left, % from the right.

Use parameter expansion:

#! /bin/bash

strings=('Job with id 0 ended with status COMPLETED, return code 16, in 1 minute 12 seconds'
         'Job with id 0 COMPLETED with return code 255'
        )

for string in "${strings[@]}" ; do
    code=${string#*return code }
    code=${code%,*}
    echo $code
done

# removes pattern from the left, % from the right.

Use parameter expansion:

#! /bin/bash

strings=('Job with id 0 ended with status COMPLETED, return code 16, in 1 minute 12 seconds'
         'Job with id 0 COMPLETED with return code 255'
        )

for string in "${strings[@]}" ; do
    code=${string#*return code }
    code=${code%%[!0-9]*}
    echo $code
done

# removes pattern from the left, % from the right.

Source Link
choroba
  • 49.4k
  • 7
  • 92
  • 118

Use parameter expansion:

#! /bin/bash

strings=('Job with id 0 ended with status COMPLETED, return code 16, in 1 minute 12 seconds'
         'Job with id 0 COMPLETED with return code 255'
        )

for string in "${strings[@]}" ; do
    code=${string#*return code }
    code=${code%,*}
    echo $code
done

# removes pattern from the left, % from the right.