0

I have a grep that returns me a text file in the following format:

filename1.txt:14
filename1.txt:17
filename2.txt:10

I want to write a scripts so that I can generate a text in the following format:

filename1.txt 14 17
filename2.txt 10

How can I extract those numbers in bash?

1 Answer 1

1

You can use awk for this:

previous_command | awk -F':' '{x[$1] = x[$1]" "$2} END {for (f in x) print f""x[f]}'

If previous_command produces:

filename1.txt:14
filename1.txt:17
filename2.txt:10

Then the result will be:

filename2.txt 10
filename1.txt 14 17

If you also want the result to be alphabetically ordered then just pipe that to sort:

previous_command | awk -F':' '{x[$1] = x[$1]" "$2} END {for (f in x) print f""x[f]}' | sort

Result:

filename1.txt 14 17
filename2.txt 10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.