shell parsing a line to look for a certain tag

前端 未结 3 435
执念已碎
执念已碎 2021-01-26 02:15

I am planning to create a simple script to edit a file based on values stored within a properties file. So essentially I am planning to loop through each line in the original fi

相关标签:
3条回答
  • 2021-01-26 02:28

    For instance you can search for strings and manipulate them in one step using sed the stream editor.

    echo $line | sed -rn 's:^.*/#(certs.+):\1:p'
    

    This will print only the relevant parts after the /# of the relevant lines.

    0 讨论(0)
  • 2021-01-26 02:35

    This is portable to Bourne shell and thus, of course, ksh and Bash.

    case $line in
        '/#'* ) tag="${line#/\#}" ;;
    esac
    

    To put it into some sort of context, here is a more realistic example of how you might use it:

    while read line; do
        case $line in
            '/#'* ) tag="${line#/\#}" ;;
            *) continue ;; # skip remainder of loop for lines without a tag
        esac
        echo "$tag"
        # Or maybe do something more complex, such as
        case $tag in
            cert)
               echo 'We have a cert!' >&2 ;;
            bingo)
               echo 'You are the winner.' >&2
               break # terminate loop
               ;;
            esac
    done <$OLD_FILE >$NEW_FILE
    
    0 讨论(0)
  • 2021-01-26 02:41

    You can use BASH regex capabilities:

    while read line
    do
    if [[ "$line" =~ ^.*/#certs(.*)$ ]]; then
        # do your processing here 
        # echo ${BASH_REMATCH[1]} is the part after /#certs
        echo echo ${BASH_REMATCH[1]} >> ${NEW_FILE}
    fi
    done < ${OLD_FILE}
    
    0 讨论(0)
提交回复
热议问题