awk find and print next string

Can I do this in one awk session. Solution I have is poor.

I want to return the number after PID.

echo "Start: 12345 is used by PID:11111 username" | awk -F: '{print $3}' | awk '{print $1}'

One way

$ echo "Start: 12345 is used by PID:11111 username" | awk -F":" '/PID/{print $2}' RS=" "
11111
$ echo "Start: 12345 is used by PID:11111 username" | awk  'gsub(/.*PID:|username/,x)'
11111
$ echo "Start: 12345 is used by PID:11111 username" | awk  '{split($6,A,":");print A[2]}'
11111
1 Like

Nice solution. Thanks.

I understand that RS is setting a new line but why is username not printed?

Sorry I thought you want only PID

$ echo "Start: 12345 is used by PID:11111 username" | awk  'gsub(/.*PID:/,x)'
11111 username
$ echo "Start: 12345 is used by PID:11111 username" | awk  '{split($0,A,"PID:");print A[2]}'
11111 username
$ echo "Start: 12345 is used by PID:11111 username" | awk -F"PID:" '{print $2}'
11111 username

Hello,

Some more approaches.

echo "Start: 12345 is used by PID:11111 username" | grep -Po  '(?<=PID:).*'
11111 username
echo "Start: 12345 is used by PID:11111 username" | sed 's/\(.*PID:\)\(.*\)/\2/g'
11111 username
 echo "Start: 12345 is used by PID:11111 username" | awk 'gsub(/.*:/,X,$0) {print $0}'
11111 username

Thanks,
R. Singh

1 Like

No - your solution was perfect. I didn't want username.

Was just trying to understand why using

FS = " " 

did not return:

11111
username

Default FS is space no need of defining it, if you want to use some other field separator such as tab,comma,etc then you have to define it

$ echo "Start: 12345 is used by PID:11111 username" | awk '{gsub(/.*PID:/,x);print $1 "\n" $2}'
11111
username


$ echo "Start: 12345 is used by PID:11111 username" | awk '{gsub(/.*PID:/,x);print $1 RS $2}'
11111
username

default RS is "\n"