I have a log file that has lines that look like this:

blah blah blah Photo for (702049679 - blah blah blah

Now I know I could get all the lines like that from the file by doing:

grep "Photo for" logFile

But how can I take those lines and get a comma seperated list of each number after the parenthesis in a single output line (these are going to be pasted into an SQL query)?

The numbers in question will be the first occurrence of a string of numeric characters 9 or more digits long. Ideally it could be matched using that criteria, or the criteria of the first number occurring after the "Photo for (" text.

  • Could you be more specific about the input data? blah blah blah is pretty nondescript and vague... – jasonwryan Jan 31 '14 at 0:31
  • @jasonwryan Updated. – Muhd Jan 31 '14 at 0:34

A regex this complicated is better handled with Perl, e.g.

grep "Photo for" logFile | perl -pe 's/.*Photo for ((\d+).*/\1/' | tr '\n' ','

If Perl is out of the question:

grep "Photo for" logFile | awk '{sub(/.*Photo for \(/,"",$0);sub(/[ ].*/,"");print $0}' | tr '\n' ','
| improve this answer | |
  • First one works... second one gives awk: fatal: Unmatched ( or \(: /.*Photo for (/. Thanks though, problem solved. EDIT: Second just needs that parenthesis escaped with \. – Muhd Jan 31 '14 at 0:42
  • I fixed the second answer (I added "Photo for" to the regex at the last minute when you edited the post) – samiam Jan 31 '14 at 0:59

An alternative that uses only Perl and matches the criteria you specified:

perl -ne '
    /Photo for/ && /([0-9]{9,})/ && push @numbers,$1;
    END{ $" = ","; print "@numbers" }
' logFile

This will print out a comma-separated list of the first occurrence of a contiguous digit string made up of 9 or more digits on each line matching Photo for.

| improve this answer | |

1) need gnu grep

grep -iPo "(?<=Photo for \()[0-9]+" logFile|tr "\n" ","

2) Using awk

awk -F \( '/Photo for/{split($2,a,OFS);printf a[1] ","}' logFile
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.