Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using awk to extract and split

i am trying to extract a substring with awk from a command answer in bash

example output line: abc_def_ghi jkl_lmn_opq

getting the second part is easy by

echo abc_def_ghi jkl_lmn_opq | awk '{print $2}'

but i only need the last part substring "opq" and didn't find a way to let awk run twice over the string, when i pass the result from above to a var and use this var for second awk i get an error because the string is a path and therefore a Directory. too i didn't get sed to work with the same error when used on a stored var with the string and i did not manage to pass first substring to second awk or sed. weird?

this would do the Job if not first awk would print out instead of passing to second awk

echo abc_def_ghi jkl_lmn_opq | awk '{print $2}' | awk -F"_" '{print $3}'

works neither

echo abc_def_ghi jkl_lmn_opq | awk '{$2}' | awk -F"_" '{print $3}'

how can i pass it right to secondly strip?

like image 769
peet Avatar asked Jun 05 '13 05:06

peet


1 Answers

This should work:

$ echo abc_def_ghi jkl_lmn_opq | awk -F_ '{ print $NF}'
opq

NF is a built-in variable that stores number of fields. When you split the line with _ and tell awk to print $NF you will print the last field.

However, you might not always need last part of the string. In that case you can use substr function in awk.

Using same example, you can do:

$ echo abc_def_ghi jkl_lmn_opq | awk ' { print substr($2,9) }'
opq

substr function takes 3 arguments, the third being optional. First argument is the string in question. Second argument is the starting point and third (optional) argument is the length you want to capture. If you don't provide it then by default it will capture everything until the end of string.

like image 100
jaypal singh Avatar answered Sep 18 '22 06:09

jaypal singh