Parsing command line output delimited by underscore

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?

Artem

Posted 2013-01-14T05:47:45.450

Reputation: 125

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 – 2013-01-14T07:21:33.010

Answers

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

slm

Posted 2013-01-14T05:47:45.450

Reputation: 7 449

1

some solutions:

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

.

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

.

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

sparkie

Posted 2013-01-14T05:47:45.450

Reputation: 2 110

1

sed 's/^[^:]*:[^_]*_[^_]*_[^_]*_//'

Nicole Hamilton

Posted 2013-01-14T05:47:45.450

Reputation: 8 987

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.

glenn jackman

Posted 2013-01-14T05:47:45.450

Reputation: 18 546