How to cut a string after a specific character in unix

前端 未结 7 625
说谎
说谎 2020-12-08 14:30

So I have this string:

$var=server@10.200.200.20:/home/some/directory/file

I just want to extract the directory address meaning I only wan

相关标签:
7条回答
  • 2020-12-08 14:50

    This should do the trick:

    $ echo "$var" | awk -F':' '{print $NF}'
    /home/some/directory/file
    
    0 讨论(0)
  • 2020-12-08 14:56

    This will also do.

    echo $var | cut -f2 -d":"
    
    0 讨论(0)
  • 2020-12-08 15:01
    awk -F: '{print $2}' <<< $var
    
    0 讨论(0)
  • 2020-12-08 15:04

    This might work for you:

    echo ${var#*:}
    

    See Example 10-10. Pattern matching in parameter substitution

    0 讨论(0)
  • 2020-12-08 15:06

    For completeness, using cut

    cut -d : -f 2 <<< $var
    

    And using only bash:

    IFS=: read a b <<< $var ; echo $b
    
    0 讨论(0)
  • 2020-12-08 15:10

    You don't say which shell you're using. If it's a POSIX-compatible one such as Bash, then parameter expansion can do what you want:

    Parameter Expansion

    ...

    ${parameter#word}

    Remove Smallest Prefix Pattern.
    The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the prefix matched by the pattern deleted.

    In other words, you can write

    $var="${var#*:}"
    

    which will remove anything matching *: from $var (i.e. everything up to and including the first :). If you want to match up to the last :, then you could use ## in place of #.

    This is all assuming that the part to remove does not contain : (true for IPv4 addresses, but not for IPv6 addresses)

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