Replace keyword with its filename without extension : bash script
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
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]
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 .
1
2
3
4
5
|
#!/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
1
|
ls -1 *.txt > txtlist
|
Create a file sharad.sh and paste the below given content. replace the keyword as per your scenario.
1
2
3
4
5
|
#!/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
No comments:
Post a Comment