rigidfence
rigidfence

Reputation: 335

Find the first column which starts with a string

I have a bash script which is going to receive a string that looks something like this:

foo,user:johndoe,bar

The order and number of values is not known, so it could also be something like:

bar,foo,baz,user:johndoe

I need to be able to get the name of the user -- in this case, johndoe.

With grep the closest I have gotten is this:

$ echo "foo,user:johndoe,bar" | grep -o 'user:.*,'
user:johndoe,

But this also gets me user: and ,, which I don't want. I am new to this and am not sure if grep is the tool I should be using, or if awk or something is more appropriate.

Upvotes: 1

Views: 335

Answers (3)

pankajgupta
pankajgupta

Reputation: 1

echo "foo,user:johndoe,bar" | awk -F ":" '{print $2}' | awk -F "," '{print $1}'

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47099

For simple substitutions sed will do:

% echo "foo,user:johndoe,bar" | sed 's/.*user:\([^,]*\).*/\1/'
johndoe

The above will replace the whole string with your user:

s/
  .*                     # Match anything zero or more times
    user:                # Match literal user:
         \([^,]*\)       # Capture everything but , zero or more times in \1
                  .*     # Match to the end of the string
                    /\1/ # Replace with what we matched and saved in \1

GNU Grep also have a -P option which enables PCRE that support lookbehinds:

% echo "foo,user:johndoe,bar" | grep -Po '(?<=user:)[^,]*'
johndoe

-P is still highly experimental and should be avoided when possible.

Upvotes: 3

John1024
John1024

Reputation: 113814

With awk:

$ echo "foo,user:johndoe,bar" | awk -F: '$1=="user"{print $2}' RS=,
johndoe

How it works

  • -F:

    This sets the field separator to :

  • $1=="user"{print $2}

    If the first field is user, then print the second field.

  • RS=,

    This sets the record separator to ,.

Upvotes: 2

Related Questions