Find and Grep in Script - almost there
Hi - I need a bit of help with the final piece of a little bash script.
I need to traverse through a directory and its subdirectories looking for files that end with .txt. I need to grep through the found .txt files and print out a particular line, followed by the path and filename of the file itself. For starters, from a terminal, when I do this: Code:
find . -name *.txt | xargs grep metadate* ./directory/filename.txt:metadate20061212 What I need is for the metadate to come first, then the file location and name like this: metadate20061212:./directory/filename.txt Here is script I have so far: Code:
#!/bin/sh metadate20061212 ./directory/filename.txt If someone could help me tweak the script so it outputs everything on one line I would be very appreciative. Or if there is a better way to do this, I would love to know it -- learning BASH never ends. Thanks! |
Assuming GNU grep on Linux:
Code:
sed 's/\(.*\):\(.*\)/\2:\1/' <(grep -rF meta --include="*.txt" *) Code:
while IFS=: read a b;do echo "$b":"$a"; done< <(grep -rF meta --include="*.txt" *) |
find . -name *.txt | xargs grep metadate* | awk -F ':' '{print $2 "\n" $1 "\n"}'
|
how about
Code:
find . -name "*.txt" -exec grep "metadate*" {} \; |
Quote:
Quote:
Quote:
|
something like this ?
Code:
for file in `find . -name '*.txt'` |
something like this ?
Code:
for file in `find . -name '*.txt'` |
for safety you should always quote when using the -name option
-name '*.txt' so the glob isn't expanded by the shell for instance if you have a *.txt in your current working directorry. |
Wow, thanks for all the great responses. Clearly, I have a lot of Bash learning to do. :-)
Anyway, I ended up using radoulov's second piece of code: Code:
while IFS=: read a b;do echo "$b":"$a"; done< <(grep -rF meta --include="*.txt" *) Thanks again, everyone. This has been very helpful and educational. |
All times are GMT -5. The time now is 03:48 PM. |