6

I have a string like this

<user>@<server>:<port>:/foo/bar

and I would like to extract the user, server, port and directory.

The user can easily be extracted by

echo <string> | awk -F"@" '{print $1;}'

But the server lies within two different delimeters. Is this possible via awk?

9

You can combine two cut commands to extract the server name:

echo <string> | cut -d":" -f1 | cut -d"@" -f2

Explanation:

  • echo <string> | use the string as input
  • cut -d":" -f1 | set field delimiter to : and extract the first field (<user>@<server>)
  • cut -d"@" -f2 set filed delimiter to @ and extract the secon field (<server>)
2
  • A brief explanation of the arguments used would be awesome in the answer.
    – edigu
    Oct 1 '18 at 21:50
  • @edigu thanks for the note. I edited my answer
    – Wayne_Yux
    Oct 2 '18 at 8:07
7

Yes it is possible - using a regular expression for the delimiter

$ echo '<user>@<server>:<port>:/foo/bar' | awk -F'@|:' '{print $1; print $2; print $3;print $4;}'
<user>
<server>
<port>
/foo/bar

or

$ echo '<user>@<server>:<port>:/foo/bar' | awk -F'[@:]' '{print $1; print $2; print $3;print $4;}'
<user>
<server>
<port>
/foo/bar
2

How about only,

grep -Eoi "[a-z/]{1,}"  <<< "<user>@<server>:<port>:/foo/bar"
user
Server
port
/foo/bar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.