0

I receive a huge textfile generated with find.

The contents of the generated textfile are a file-referenes with full path, i.e.:

//server/dir1/dir1foobar.ext
//server/dir1/dir2/dir1bar.ext
//server/dir1/dir2/dir1.ext
//server/dir3/dir4/dir4.ext
//server/dir5/dir6/dir7/dir1foo.ext
//server/dir1/dir2/dir3/dir2.ext
//server/dir3/dir4/dir5/dir6/dir3.ext

(filenames and paths are kinda random, so I can't start always at position n from the begining or the end of a line)

I need to grep this textfile for a specific pattern, write the results (which needs to be a complete line for a match) into a new (sorted with sort) file, but also need to ignore any match which is not a filename.

So, with my example-lines above, I have a search pattern "dir1" and the result must be a new file containing those lines:

//server/dir1/dir1foobar.ext
//server/dir1/dir2/dir1bar.ext
//server/dir1/dir2/dir1.ext
//server/dir5/dir6/dir7/dir1foo.ext

My attempts with sort -f -u $textfile | grep -i $pattern > $newfile were not successful, because grep has a match too when the directory contains the pattern, which will result in a "false" match for //server/dir1/dir2/dir3/dir2.ext.

I read in grep manual that regex is possible with option -G but could'nt fiddle out any way to grep only in the filenames part of a line.

2

Try grepping like this:

grep -i 'dir1[^/]*$'

Which means it will only accept the match if it matches dir1, and that match is not followed by any / until the end of the line.

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.