Pregunta

I'm stumped with how to remove a portion of a string that has forward slashes and question marks in it.

Example: /diag/PeerManager/list?deviceid=RXMWANT8WFYJNF7K6DXXXJLJVN

and I need the output to be RXMWANT8WFYJNF7K6DXXXJLJVN

I've tried tr and sed but tr removes some of the characters I need in the output. sed is giving me trouble because of the forward slashes.

What's a quick method to remove the /diag/PeerManager/list?deviceid= portion of my string? thanks!

¿Fue útil?

Solución

This worked for me:

sed 's/.*deviceid=\([^&]*\).*/\1/'

Example:

$ echo '/diag/PeerManager/list?deviceid=RXMWANT8WFYJNF7K6DXXXJLJVN' | sed 's/.*deviceid=\([^&]*\).*/\1/'
RXMWANT8WFYJNF7K6DXXXJLJVN

This is not the most robust solution, but if you have a fixed set of input that will never change, it's probably good enough.

Otros consejos

echo "/diag/PeerManager/list?deviceid=RXMWANT8WFYJNF7K6DXXXJLJVN" | sed -n 's:/[a-zA-Z]/[a-zA-Z]/[a-zA-Z]?[a-zA-Z]=::p'

This should do the trick. I chose the colon as the delimiter as it will not cause any issues with the forward slash. This makes a lot of assumptions about the type of input it will be receiving, specifically that it will only contain three backslashes with lower and uppercase letters between them, a series of letters ending in a question mark, another series of letters ending in an equals sign. This then removes those items and prints the remaining characters (your device id).

One way using awk, if there is only a single occurrence of an = on each line:

awk -F= '{ print $2 }' file.txt

Results:

RXMWANT8WFYJNF7K6DXXXJLJVN

Use Equals Sign as Field Delimiter

If you know that your GET query string will always have only one parameter (in this case, deviceid) then you can just use the equals sign as a field delimiter with the standard cut utility. For example:

$ echo '/diag/PeerManager/list?deviceid=RXMWANT8WFYJNF7K6DXXXJLJVN' |
    cut -d= -f2-
RXMWANT8WFYJNF7K6DXXXJLJVN

How about:

$ echo /diag/PeerManager/list?deviceid=RXMWANT8WFYJNF7K6DXXXJLJVN | sed 's/^.*=//'
RXMWANT8WFYJNF7K6DXXXJLJVN
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top