4

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.

3 Answers 3

8

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
2
  • Thanks @steeldriver for your answer. Can I perform shell like operation such as tr and cut inside awk? Commented Feb 2, 2021 at 15:22
  • 1
    @user280009 yes it's possible, you can use Redirection to pipe data to a command, and in some implementation even use Two-Way Communications with Another Process to read the results back into awk for futher processing Commented Feb 2, 2021 at 15:48
6

With any sed:

$ sed 's:.*/\(.*_\(.*\)\)\..*:\1 \2:' file
file_name_delimited_by_underscore_123 123
another_example_456 456
3

You can use sed:

$ sed -e 's;^.*/\(.*_\)\([0-9]*\)\.[^\.]*$;\1_\2 \2;' file
file_name_delimited_by_underscore_123 123
another_example_456 456

^.*/ deletes the path.

\(.*_\) captures the name until the last underscore.

\.[^\.]* removes the extension.

\1\2 \2 replace by the captured groups.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.