Operations on AWK Fields

awk

I have a file that contains full paths:

/home/usr/file_name_delimited_by_underscore_123.txt  
/home/usr/another_example_456.rar

I would like to print the file name from the path without the extension and to print next to it the string after the last _.

Output:

file_name_delimited_by_underscore_123 123
another_example_456 456

I figured a way to get the desired output using piped awk commands:

cat file | awk -F[/.] '{print $(NF-1)}' | awk -F_ '{print $0" "$NF}'

Is there a way to achieve this without piping?

My question boils down to is it possible to perform actions on the fields parsed by awk?

Thanks for your help.

Best Answer

Yes, you can perform any operations you like on the fields. For example:

$ cat file | awk -F[/.] '{n = split($(NF-1),a,/_/); print $(NF-1)" "a[n]}'
file_name_delimited_by_underscore_123 123
another_example_456 456

Of course, you don't need cat here; you could have awk read the file directly - and since the default output field separator OFS is a space, it would be more idiomatic to write the results as separate output fields instead of a string concatenation:

awk -F[/.] '{n = split($(NF-1),a,/_/); print $(NF-1), a[n]}' file
Related Question