Today in this example we will use bash script. The task is replace keyword with its filename without extension.To accomplish this task we will use bash script.In bash script we will use for loop and sed command .To elaborate this example,lets assume we have 4 files called

file1.txt
red.txt
blue.txt
roger.txt

The above each file has keyword called hello in its content. Hence we will replace hello keyword with its own filename but without extension.
For example. in red.txt , hello keyword will be replaced with red [note: red is file name without extension]

I am writing two scripts which do same job, you can use anyone at one time

Bash script 1: Create a file test.sh and paste the below given content. replace the keyword as per your scenario .

#!/bin/bash
for i in *.txt
do
sed -i -e "s,hello,${i/.txt/},g" $i
done

After saving the file,give permission chmod 750 test.sh

Now run the script by typing sh test.sh

Bash script 2:

First change to directory where you want to do this practical.Then list the filename in txtlist file

ls -1 *.txt > txtlist

Create a file sharad.sh and paste the below given content. replace the keyword as per your scenario.

#!/bin/bash
for i in `cat txtlist|sed 's/.txt//g'`
do
sed -i "s/hello/$i/g" $i.txt
done

After saving the file,give permission chmod 750 sharad.sh

Now run the script by typing sh sharad.sh

Read Some More Articles

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.