Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract a string after a pattern

I want to extract the numbers following client_id and id and pair up client_id and id in each line.

For example, for the following lines of log,

User(client_id:03)) results:[RelatedUser(id:204, weight:10),_RelatedUser(id:491,_weight:10),_RelatedUser(id:29, weight: 20)

User(client_id:04)) results:[RelatedUser(id:209, weight:10),_RelatedUser(id:301,_weight:10)

User(client_id:05)) results:[RelatedUser(id:20, weight: 10)

I want to output

03 204
03 491
03 29
04 209
04 301
05 20

I know I need to use sed or awk. But I do not know exactly how.

Thanks

like image 672
jerry Avatar asked Nov 20 '12 00:11

jerry


People also ask

How do I extract a string after a specific string in Python?

Using split() to get string after occurrence of given substring. The split function can also be applied to perform this particular task, in this function, we use the power of limiting the split and then print the later string.

How do you extract a string from a string?

To extract a substring that begins at a specified character position and ends before the end of the string, call the Substring(Int32, Int32) method. This method does not modify the value of the current instance. Instead, it returns a new string that begins at the startIndex position in the current string.

How do you get a specific string in Python?

Python String find() method. Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found, then it returns -1.

How do I extract a specific word from a string in R?

To extract words from a string vector, we can use word function of stringr package. For example, if we have a vector called x that contains 100 words then first 20 words can be extracted by using the command word(x,start=1,end=20,sep=fixed(" ")).


1 Answers

This may work for you:

awk -F "[):,]" '{ for (i=2; i<=NF; i++) if ($i ~ /id/) print $2, $(i+1) }' file

Results:

03 204
03 491
03 29
04 209
04 301
05 20
like image 123
Steve Avatar answered Nov 23 '22 14:11

Steve