Avishek
Avishek

Reputation: 3

Shell script - replace a string in the all the files in a directory based on file name

I want to replace a constant string in multiple files based on the name of the file.

Example: In a directory I have many files named like 'X-A01', 'X-B01', 'X-C01'. In each file there is a string 'SS-S01'. I want to replace string 'SS-S01' in the first file with 'X-A01', second file with 'X-B01' and third file with 'X-C01'.

Please help me how can we do it as I have hundreds of files like this and do not want to manually edit all files one by one.

Upvotes: 0

Views: 72

Answers (1)

dvaergiller
dvaergiller

Reputation: 815

Remember to back up your files(!) before running this command, since I have not actually tried it myself:

You could do something like:

for file in <DIR>/*; do sed -i "s/SS-S01/${file##*/}/" "$file"; done

This will loop over each file in <DIR> and for each loop iteration assign the file name to $file. For each file, sed will replace the first occurence of SS-S01 in that file by the file name.

Upvotes: 1

Related Questions