How can I assign the match of my regular expression to a variable?

前端 未结 5 644
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-07 06:34

I have a text file with various entries in it. Each entry is ended with line containing all asterisks.

I\'d like to use shell commands to parse this file and assign each

5条回答
  •  旧时难觅i
    2021-02-07 07:16

    Splitting records in (ba)sh is not so easy, but can be done using IFS to split on single characters (simply set IFS='*' before your for loop, but this generates multiple empty records and is problematic if any record contains a '*'). The obvious solution is to use perl or awk and use RS to split your records, since those tools provide better mechanisms for splitting records. A hybrid solution is to use perl to do the record splitting, and have perl call your bash function with the record you want. For example:

    #!/bin/bash
    
    foo() {
        echo record start:
        echo "$@"
        echo record end
    }
    export -f foo
    
    perl -e "$/='********'; while(<>){chomp;system( \"foo '\$_'\" )}" << 'EOF'
    this is a 2-line
    record
    ********
    the 2nd record
    is 3 lines
    long
    ********
    a 3rd * record
    EOF
    

    This gives the following output:

    record start:
    this is a 2-line
    record
    
    record end
    record start:
    
    the 2nd record
    is 3 lines
    long
    
    record end
    record start:
    
    a 3rd * record
    
    record end
    

提交回复
热议问题