Issue
Given a list of directories and/or file paths, I want to extract the paths of the directories containing files with names matching a given pattern, e.g. files having a .txt
extension.
Sample input file:
/a/b/c/d.txt
/a/b/c/d/e.txt
f
g
h/i
/a/b/c.txt
Expected output:
/a/b/c/
/a/b/c/d/
/a/b/
How do I do this with Linux command line tools? I'm wondering if the following is a good start:
grep "\.txt" foo | <what else?>
Solution
(Assuming the desired output has a trailing /
on the 2nd and 3rd lines, otherwise it's inconsistent with the 1st line of output...)
Look at this:
sed -En '/\.txt$/s!(.*/).*!\1!p' foo
where
-E
is to use(
and)
instead of\(
and\)
for grouping-n
tells Sed not to print the pattern space by default/\.txt$/
only matches those lines ending by.txt
s
run a substitution on those lines we matched with/\.txt$/
!
is used instead of/
as a separator, because so we don't have to escape/
(.*/).*
matches the whole line, but captures only up to and including the last/
\1
replaces the line with the part that we catpured- the
p
flag tells Sed to print the line
Answered By - Enlico Answer Checked By - David Marino (WPSolving Volunteer)