Bob
Bob

Reputation: 571

Edit all files in a directory and save as another copy

I have 4 files in a directory "dir" called "a.txt", "b.txt" and "c.txt". All the files contain text.

a.txt: The Chan Chan Man was arrested.

b.txt: Chandler Bing got arrested.

c.txt: Joey, duck and chick protested against the Chandler's arrest.

I want to delete specific keywords from all the files and store these new files in another directory "dir2". Lets say I want to delete "arrest" and "arrested". So new files become:

aNew.txt: The Chan Chan Man was .

bNew.txt: Chandler Bing got .

cNew.txt: Joey, duck and chick protested against the Chandler's .

I am using Mac Terminal. It would be great if some one can give a solution for general case where files could in subdirectories and I could provide list of regular expression instead of keywords to delete.

Upvotes: 1

Views: 75

Answers (1)

R Sahu
R Sahu

Reputation: 206717

#!/bin/bash

source=dir
dest=dir2

for file in a.txt b.txt c.txt
do
   # Copy the file to the destination directory
   cp "$source/$file" "$dest"

   # Modify the contents of the file in the destination directory.
   sed -i 's/arrested\././' "$dest/$file"
   sed -i 's/arrest\././' "$dest/$file"
done

Upvotes: 1

Related Questions