views:

109

answers:

6

Hello,

I have following string

â   â³ eGalax Inc. USB TouchController          id=9    [slave  pointer  (2)]
â   â³ eGalax Inc. USB TouchController          id=10   [slave  pointer  (2)]

and would like to get the list of id ? How this can be done using sed or something else ?

Regards, Levon

+1  A: 

I pasted the contents of your example into a file named so.txt.

$ cat so.txt | awk '{ print $7 }' | cut -f2 -d"="
9
10

Explanation:

  1. cat so.txt will print the contents of the file to stdout.
  2. awk '{ print $7 }' will print the seventh column, i.e. the one containing id=n
  3. cut -f2 -d"=" will cut the output of step #2 using = as the delimiter and get the second column (-f2)

If you'd rather get id= also, then:

$ cat so.txt | awk '{ print $7 }' 
id=9
id=10
Manoj Govindan
Thaks this is exactly what I wanted !
deimus
you can accept this as the answer then.
Vijay Dev
useless use of cat and cut. awk can do all of it.
@user229426: You mean _unnecessary_ use of cat and cut, not _useless_, don't you?
Manoj Govindan
A: 

Use a regular expression to catch the id number and replace the whole line with the number. Something like this should do it (match everything up to "id=", then match any number of digits, then match the rest of the line):

sed -e 's/.*id=\([0-9]\+\).*/\1/g'

Do this for every line and you get the list of ids.

bluebrother
this method gives 9 and 1 but it should be 9 and 10
deimus
Right, I've made a mistake when pasting the sed line. Updated it to work correctly.
bluebrother
+1  A: 

A perl-solution:

perl -nE 'say $1 if /id=(\d+)/' filename
sid_com
+1  A: 

You can have awk do it all without using cut:

awk '{print substr($7,index($7,"=")+1)}' inputfile

You could use split() instead of substr(index()).

Dennis Williamson
+1. I like this. compact.
Manoj Govindan
A: 
$ ruby -ne 'puts $_.scan(/id=(\d+)/)' file
9
10
A: 

Assuming input of

{Anything}id={ID}{space}{Anything} 
{Anything}id={ID}{space}{Anything}

--

#! /bin/sh
while read s; do
   rhs=${s##*id=}
   id=${rhs%% *}
   echo $id # Do what you will with $id here
done <so.txt 

Or if it's always the 7th field

#! /bin/sh
while read f1 f2 f3 f4 f5 f6 f7 rest
do
echo ${f7##id=}
done <so.txt

See Also

Shell Parameter Expansion

Frayser