Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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
up vote 1 down vote accepted

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 $_;'

Works as follows:

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

search and replace


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


Matches 3 of them


replaces them with nothing (i.e. deletes)


print what's left of $_

print $_
share|improve this answer
sed 's/^[^:]*:[^_]*_[^_]*_[^_]*_//'
share|improve this answer

some solutions:

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


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


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

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



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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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