Sasha Desansky
Sasha Desansky

Reputation: 71

How do I loop through files in a directory with a specific prefix and replace a specific word in those files?

I have files in a directory and they start with a prefix "TESTFILE.".

How do I loop through those files with that prefix and replace a specific word with another word in just those files?

I have tried the below code and it changes all filed in the directory, not just files with that prefix. I need to change files with just that prefix.

for i in *TESTFILE.*; do sed -i 's/oldword/newword/g' * ;done

If I have files in a directory:

TESTFILE.file1
TESTFILE.file2
OTHER.file3

and their body contains: "Let's replace this oldword"

Inside the body of those files, I want "oldword" to be changed to "newword" only in files that start with "TESTFILE.".

Upvotes: 0

Views: 1992

Answers (2)

UtLox
UtLox

Reputation: 4154

Here is a robust version that gets along with blank characters in the file name:

#!/bin/bash
while IFS= read -r -d '' file; do
    sed -i 's/oldword/newword/g' "$file"
done < <(find . -type f -name 'TESTFILE.*' -print0)

Upvotes: 0

melpomene
melpomene

Reputation: 85767

The problem is that your loop body ignores the loop variable (i) and just runs sed on everything (*).

Fix:

for i in TESTFILE.*; do sed -i 's/oldword/newword/g' -- "$i"; done

Or even just

sed -i 's/oldword/newword/g' TESTFILE.*

if you don't have too many files to fit into a single command line.

Upvotes: 1

Related Questions