user607694
user607694

Reputation: 73

How to extract word from a string that may/may not start with a single quote

Sample string:

'kernel-rt|kernel-alt|/kernel-' 'headers|xen|firmware|tools|python|utils'

cut -d' ' -f 1 string.txt gives me

'kernel-rt|kernel-alt|/kernel-'

But how do we proceed further to get just the 'kernel' from it?

Upvotes: 0

Views: 51

Answers (2)

Dudi Boy
Dudi Boy

Reputation: 4900

Assuming you want only the 3rd kernel (in bold) and not the others

'kernel-rt|kernel-alt|/kernel-' 'headers|xen|firmware|tools|python|utils'

Here is how you extract it using single command awk (standard Linux gawk).

input="kernel-rt|kernel-alt|/kernel-' 'headers|xen|firmware|tools|python|utils"

echo $input|awk -F"|" '{split($3,a,"-");match(a[1],"[[:alnum:]]+",b);print b[0]}'

explanation

-F"|" specify field separator is | so that only is 3rd field required

split($3,a,"-") split 3rd field by -, left part assigned to a[1]

match(a[1],"[[:alnum:]]+",b) from a[1] extract sequence of alphanumeric string into b[0]

print b[0] output the matched string.

If you want to extract kernel from 2nd or 1st fields. Change $3 to $2 or $1.

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 204259

$ cat file
'kernel-rt|kernel-alt|/kernel-' 'headers|xen|firmware|tools|python|utils'
$
$ awk '{print $1}' file
'kernel-rt|kernel-alt|/kernel-'
$
$ awk '{gsub(/\047/,"",$1); print $1}' file
kernel-rt|kernel-alt|/kernel-
$
$ awk '{gsub(/\047/,""); split($1,f,/[|]/); print f[1]}' file
kernel-rt

and just to make you think...

$ awk '{gsub(/\047|\.*/,"")}1' file
kernel-rt

Upvotes: 1

Related Questions