1

Summary: I have a substring extraction problem that I am just failing on. I have a string that has an indeterminate multiple of people's names that I want to extract. Within the string, these substrings are fairly well defined, but the random number of substrings, the random lengths of the substrings, and my midling Bash skill is just overwhelming me.

Context: I have used exiftool to extract the checked tags from files processed by DigiKam to produce my source string. I think this fact is fairly immaterial to the problem at hand, but provided for completeness.

String Examples

tagoutput="Tags List                       : Date/Month/March, Places/Our House, People/FirstName1 LastName1, People/FirstName2 LastName2, Date/Year/2009, Date/Day/22"
tagoutput="Tags List                       : People/FirstName1 LastName1, Date/Year/1970, Date/Month/Feburary, Places/Grandmas House"

Notes: As you can see, within the string, things are well formatted, but can come in random orders and in unknown quantities. Another FYI is in each of the above examples between List and the colon, there is a significant white space (~25 spaces) that posting here is autoremoving.

What I need: Given $tagoutput, I want to echo to console

FirstName1 LastName1
FirstName2 LastName2
...

for each of the names in $tagoutput. I have this in a "For each file in Directory loop" where I extract $tagoutput immediately before refining $tagoutput for the names. Since this problem is so file centric, I chose to use Bash, but if the correct answer here is to go to a better suited language like Python, I am not married to it.

1
  • Yes, $tagoutput is a script variable, completely arbitary. Commented Jun 12, 2020 at 5:04

1 Answer 1

2

With GNU grep, you could just do:

grep -Po ' People/\K[^,]*' <<< $tagoutput

This matches every occurence of People/ (preceded by a white space), and extracts zero or more non-comma characters following it.

Sign up to request clarification or add additional context in comments.

1 Comment

@oguzismail : The \K trick is fantastic! The first time I see a really good use of perlre in grep.

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.