sh - Easiest way in Bourne shell to extract strings from a line of text?

07
2014-07
  • CaptSaltyJack

    Let's say I'm doing a grep and it returns this line:

    Invalid value (48) on line 3
    

    How can I easily pull that value 48 into a variable in Bourne shell?

  • Answers
  • johnshen64

    If you are sure that the pattern is always to get the value in the first pair of parenthesis, then cut is your best friend.

    myvar=$(echo 'Invalid value (48) on line 3' | cut -d\( -f2 | cut -d\) -f1)
    

    this extracts the value between the parens.

  • Etan Reisner

    echo 'Invalid value (48) on line 3'| awk -F'[()]' '{print $2}'


  • Related Question

    bash - sh alias: command not found
  • Anthony Kong

    I have written a very simple script like this:

    function apply_to_dev {
        echo "Applying scripts to DEV..."
        alias ISQL="isql -Uuser -Ppwd -SDEV -DDATA -I ~/bin/interfaces"
        shopt -s nullglob
        for f in ~/src/trunk/Database/scripts/upgrades/current/*.sh
        do
            echo $f
            . $f
        done
        for f in ~/src/trunk/Database/scripts/upgrades/current/*.sql
        do
            echo $f
            FOUT=`basename "$f"`
            ISQL -i "$f" -o "$LOGDIR/$FOUT.dev.out"
        done
    }
    
    apply_to_dev
    

    When I run it I got these error messages

    ~/src/trunk/Database/scripts/upgrades/current/JIRA-0192.sql
    ~/bin/RunSQL.sh: line 48: ISQL: command not found
    

    Why sh/bash will think ISQL is a command and not an alias. If I add 'alias' right after 'alias ISQL=...', I can see ISQL in the alias print out.

    Crazy enough, the *sh files in the first for loop actually calls ISQL too. The ISQL is visible inside the *.sh files.


  • Related Answers
  • petergozz

    If you must use alias ? Then it should probably be outside the script (globally as it where).

    In any case its not necessary and actually wasteful. Just rub that word out and it should work as you expect.

    BTW You could export it as a variable if you need it later on but within the same run.... (then sub shells would be able to "see" it.)

    export ISQL="isql -Uuser -Ppwd -SDEV -DDATA -I ~/bin/interfaces"

    or perhaps more tidily

    ISQL="isql -Uuser -Ppwd -SDEV -DDATA -I ~/bin/interfaces"

    export ISQL

    Not sure if thats your intention though.

    If you only want it to be local to the function, then in bash you must say so:

    local ISQL="isql -Uuser -Ppwd -SDEV -DDATA -I ~/bin/interfaces"

    $ help local

    local: local [option] name[=value] ...
        Define local variables.
    
        Create a local variable called NAME, and give it VALUE.  OPTION can
        be any option accepted by `declare'.
    
        Local variables can only be used within a function; they are visible
        only to the function where they are defined and its children.