简体   繁体   中英

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 ?

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, ie 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

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.

Perl解决方案:

perl -nE 'say $1 if /id=(\d+)/' filename
$ ruby -ne 'puts $_.scan(/id=(\d+)/)' file
9
10

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()) .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM