Amiy
Amiy

Reputation: 57

copying text from multiple files into corresponding location using shell script

I have a set of files in a directory structure like

/tmp1/folder1/file1  
/tmp1/folder2/file2

Now I want to grep some lines from both these files & create/overwrite files in a path similar to the above such that lines from the file go to the respective folder

/tmp2/folder1/grep_from_file1  
/tmp2/folder2/grep_from_file2

Upvotes: 0

Views: 210

Answers (3)

BMW
BMW

Reputation: 45353

replace the "KEY" with your expect key word in grep command:

#! /usr/bin/bash

source=/tmp1
dest=/tmp2

find $source -type f |while read file
do
  fold=${file/$source/$dest}
  fold=${fold%/*}
  name=${file##*/}
  mkdir -p $fold
  grep "KEY" $file > $fold/grep_from_$name
done

Upvotes: 1

sud03r
sud03r

Reputation: 19799

Something like this should serve the purpose:

#!/bin/bash -f

originalFiles=("/tmp1/folder1/file1" "/tmp1/folder2/file2") # Add more

for file in "${originalFiles[@]}"
do
    newDirName=`dirname $file | sed s/tmp1/tmp2/`
    newFileName=`basename $file | sed s/^/grep_from_/`
    mkdir -p $newDirName
    grep "text_to_grep" $file > $newDirName/$newFileName
done

Upvotes: 1

anubhava
anubhava

Reputation: 786359

You can use this script:

for f in tmp1/folder1/file[12]
do
    t=tmp2/"${f#*/}"
    t="${t/\///grep_from_}"
    grep "search pttern" "$f" > "$t"
done

Upvotes: 1

Related Questions