shell parsing a line to look for a certain tag

2019-03-06 12:07发布

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 file, when it comes across a certain tag within a line say "/#" it will get the text following the tag i.e. certs and then implement a function to parse through the properties file to get certain values and add them to the original file. So for example the file would have the following line:

"/#certs"

I am not sure how best to search for the tag, I was planning to have an if to find the /# and then split the remaining text to get the string.

while read line
    do

    #need to parse line to look for tag


    echo line >> ${NEW_FILE}
    done < ${OLD_FILE}

Any help would e greatly appreciated

=====================================

EDIT:

My explanation was a bit poor; apologies. I am merely trying to get the text following the /# - i.e. I just want to get the string value that precedes it. I can then call a function based on what the text is.

标签: bash shell
3条回答
何必那么认真
2楼-- · 2019-03-06 12:33

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
查看更多
手持菜刀,她持情操
3楼-- · 2019-03-06 12:46

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.

查看更多
狗以群分
4楼-- · 2019-03-06 12:53

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}
查看更多
登录 后发表回答