Search code examples
sed

How do I remove everything behind each @ in a string as long as it does not contain a / in sed?


In sed, how do I remove everything behind each @ in a string, as long as that does not contain a /?

i.e.

user@host becomes host
user:password@host becomes host
user:passw@rd@host becomes host
host:/foo@bar becomes foo@bar
host://foo@bar becomes foo@bar
user:password@host:/foo@bar becomes foo@bar

Solution

  • Using sed :

    sed 's/.*\///;t;s/.*@//' input
    
    • s - s/regexp/replacement/
    • .*\/ anything and then /
    • t from sed man page :

    If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script.

    • .*@ anything and then @

    Using perl :

    perl -i.bak -pe '!/\// && s/.*@// || s/.*\///' input