2

I've got some command which output looks like that:

some_command Current view: username_token1_token2_token3_4_token4_2

How could I parse the "token3_4_token4_2" part out of the string?

1
  • What do you mean with "parse out of the string"? Do you want to remove the token3_4_token4_2 part or do you want to extract it? – speakr Jan 14 '13 at 7:21
1

Here it is in Perl:

perl -ne '$_ =~ s/([a-zA-Z0-9]+_){3}//; print $_;'

For example:

% echo "username_token1_token2_token3_4_token4_2" | perl -ne '$_ =~ s/([a-zA-Z0-9]+_){3}//; print $_;'
token3_4_token4_2

Works as follows:

Initially the string "username_token1_token2_token3_4_token4_2" is put into the $_ variable.

search and replace

s/....//

Matches a string_ (i.e. part of the .... above)

([a-zA-Z0-9]+_)

Matches 3 of them

{3}

replaces them with nothing (i.e. deletes)

//

print what's left of $_

print $_
1
sed 's/^[^:]*:[^_]*_[^_]*_[^_]*_//'
1

some solutions:

awk -F_ '{ print $5"_"$6"_"$7"_"$8 }'

.

awk '{ print gensub("^.*_([^_]+_[^_]+_[^_]+_[^_]+)$", "\\1", "g") }'

.

awk '{ if (match($0, "_([^_]+_[^_]+_[^_]+_[^_]+)$", a)) print a[1] }'
0

Just using bash:

alias some_command='echo "some_command Current view: username_token1_token2_token3_4_token4_2"'

read a b c < <(some_command)
token=$(IFS=_; set -- $c; shift 3; echo "$*")
echo $token

prints

token3_4_token4_2

I used a process substitution to redirect the output of the command into the read statement. If I were to have used a pipe, then the read would have occurred in a subshell and the $c variable would not have existed in the parent shell.

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.