Substitution with sed + bash function

后端 未结 7 1997
一向
一向 2021-01-03 02:26

my question seems to be general, but i can\'t find any answers.

In sed command, how can you replace the substitution pattern by a value returned by a simple bash fun

相关标签:
7条回答
  • 2021-01-03 02:41

    I'd like to know if there's a way to do this too. However, for this particular problem you don't need it. If you surround the different components of the date with ()s, you can back reference them with \1 \2 etc and reformat however you want.

    For instance, let's reverse 03/04/1973:

    echo 03/04/1973 | sed -e 's/\([0-9][0-9]\)\/\([0-9][0-9]\)\/\([0-9][0-9][0-9][0-9]\)/\3\/\2\/\1/g'
    
    0 讨论(0)
  • 2021-01-03 02:44

    you can use the "e" option in sed command like this:

    cat t.sh
    
    myecho() {
            echo ">>hello,$1<<"
    }
    export -f myecho
    sed -e "s/.*/myecho &/e" <<END
    ni
    END
    

    you can see the result without "e":

    cat t.sh
    
    myecho() {
            echo ">>hello,$1<<"
    }
    export -f myecho
    sed -e "s/.*/myecho &/" <<END
    ni
    END
    
    0 讨论(0)
  • 2021-01-03 02:52

    You can glue together a sed-command by ending a single-quoted section, and reopening it again.

    sed -n 's|[0-3][0-9]/[0-1][0-9]/[0-9][0-9]|& '$(parseDates)' &|p' datefile
    

    However, in contrast to other examples, a function in bash can't return strings, only put them out:

    function parseDates(){
        # Some process here with $1 (the pattern found)
        echo dateParsed
    }
    
    0 讨论(0)
  • 2021-01-03 02:56
    sed -e 's#[0-3][0-9]/[0-1][0-9]/[0-9][0-9]#& $(parseDates &)#' myfile |
    while read -r line; do
        eval echo "$line"
    done
    
    0 讨论(0)
  • 2021-01-03 03:00

    do it step by step. (also you could use an alternate delimiter , such as "|" instead of "/"

    function parseDates(){
        #Some process here with $1 (the pattern found)
        return "dateParsed;
    }
    
    value=$(parseDates)
    sed -n "s|[0-3][0-9]/[0-1][0-9]/[0-9][0-9]|& $value &|p" myfile
    

    Note the use of double quotes instead of single quotes, so that $value can be interpolated

    0 讨论(0)
  • 2021-01-03 03:05

    Agree with Glenn Jackman. If you want to use bash function in sed, something like this :

    sed -rn 's/^([[:digit:].]+)/`date -d @&`/p' file |
    while read -r line; do
        eval echo "$line"
    done
    

    My file here begins with a unix timestamp (e.g. 1362407133.936).

    0 讨论(0)
提交回复
热议问题