LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   copy files containing specific words in a specified line (http://www.linuxquestions.org/questions/linux-newbie-8/copy-files-containing-specific-words-in-a-specified-line-665989/)

abenmao 08-28-2008 03:26 AM

copy files containing specific words in a specified line
 
Anyone knows how to use bash script to copy / move files containing particular words in a specified line to other folders?

for example:

lots of text files *.txt in a folder /tmp
I'd like to move files containing "my book" in the line 9 to another folder /home/abenmao/my book/, and move files containing a word "my dog" in the line 9 to another folder /home/abenmao/my dog/ ...

Thank you for looking into my question

indeliblestamp 08-28-2008 03:40 AM

grep with the -l switch will list only the file names. Test it first:
Code:

grep -l "my book" *
Now use cp to copy the hits to somewhere else.
Code:

cp `grep -l "my book" *` /home/abenmao/mybook/
Repeat with 'my dog' instead of 'my book'.

colucix 08-28-2008 03:47 AM

A requirement is "pattern in line 9". I would keep it simple and use a loop like this:
Code:

#!/bin/bash
while read file
do
  if sed -n 9p "$file" | grep -q "my book"
  then
    mv "$file" "/home/abenmao/my book/"
  elif sed -n 9p "$file" | grep -q "my dog"
  then
    mv "$file" "/home/abenmao/my dog/"
  fi
done < <(find /tmp -type f -name "test*")

As a general tip, I would not use blank spaces in the directory names. This makes things a bit more complicate in shell scripting. Use _ (underscore) instead.

indeliblestamp 08-28-2008 07:30 AM

ehh.. missed the line-9 requirement. Your script is pretty neat.

abenmao 08-28-2008 08:56 AM

thanks,colucix, your code worked like a charm. thanks a million! linux is really really powerful. a very long way for me to go!

abenmao 08-28-2008 09:04 AM

never expect my question will be answered in such a short time. thanks

Quote:

Originally Posted by colucix (Post 3262385)
A requirement is "pattern in line 9". I would keep it simple and use a loop like this:
Code:

#!/bin/bash
while read file
do
  if sed -n 9p "$file" | grep -q "my book"
  then
    mv "$file" "/home/abenmao/my book/"
  elif sed -n 9p "$file" | grep -q "my dog"
  then
    mv "$file" "/home/abenmao/my dog/"
  fi
done < <(find /tmp -type f -name "test*")

As a general tip, I would not use blank spaces in the directory names. This makes things a bit more complicate in shell scripting. Use _ (underscore) instead.



All times are GMT -5. The time now is 03:48 PM.