Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script : How to cut part of a string

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 ?

like image 809
deimus Avatar asked Sep 18 '10 15:09

deimus


People also ask

How do you cut a string in Unix shell script?

The cut command in UNIX is a command for cutting out the sections from each line of files and writing the result to standard output. It can be used to cut parts of a line by byte position, character and field. Basically the cut command slices a line and extracts the text.

How do I cut a string after a specific character in bash?

Open the file “input.sh” and write the appended code in the file. Here, we have declared an echo statement with the string “foo-bar-123” using the “awk” keyword. The print term is followed by the “-F-“ keyword. This will create a substring after the next special character, which is “123,” and print it.


3 Answers

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
like image 158
Manoj Govindan Avatar answered Oct 22 '22 08:10

Manoj Govindan


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.

like image 3
bluebrother Avatar answered Oct 22 '22 08:10

bluebrother


A perl-solution:

perl -nE 'say $1 if /id=(\d+)/' filename
like image 2
sid_com Avatar answered Oct 22 '22 08:10

sid_com