Reputation: 643
I am a new bie to shell scripting, here i am trying to find the text and replace the text using the shell script.
what i am trying to do is, actually i have a text file which has 2 strings separated by ": "
Like this
lorem:ipsum
dola:meru
etc....
my script will take 2 parameters while running. now the script should check if first parameter is found or not if not found it should add it to text file.
if the first parameter is found, then it should replace the second parameter.
for example
The text file has data like this
lorem:ipsum
dola:meru
caby:cemu
i am running my script with 2 parameters like this
./script.sh lorem meru
So when i run the script it should check if the first parameter found in the file if found, the script should replace the second string..
i.e I ran the script like this
./script.sh lorem meru
so in the file
lorem:ipsum
dola:meru
caby:cemu
after running the script, in the line
lorem:ipsum
should get replaced to
lorem:meru
here is what i have tried..
#!/bin/sh
#
FILE_PATH=/home/script
FILE_NAME=$FILE_PATH/new.txt
echo $1
echo $2
if [] then
else
echo $1:$2 >> $FILE_NAME
fi
Upvotes: 0
Views: 4295
Reputation: 21
You can try this as well,
input file : new.txt
lorem:ipsum
dola:meru
caby:cemu
Script file: script.sh
#!/bin/sh
sed -i "s/$1:.*/$1:$2/" new.txt
if you run the script as u wished "./script.sh lorum meru"
Output: new.txt, will be displayed as
lorem:meru
dola:meru
caby:cemu
Explanation: sed is a powerful text processing tool, where u can manipulate the text as you wish with the options it provides.
Brief explanation of the code, sed -i > used to replace the contents of the original file with the new changes ( if u dont give -i in sed it will just print the modified contents without affecting the original file)
"s/old:.*/old:new/"
"s" is used for substitution. Syntax is "s/old/new/'. Here * specifies anything that is present after the ":" So by executing this you will get the desired output.
Upvotes: 1
Reputation: 195049
try this line in your script:
awk -F: -v OFS=":" -v s="$1" -v r="$2" '$1==s{$2=r}7' file > newFile
Upvotes: 1
Reputation: 123458
Using sed
might be simpler.
$ cat inputfile
lorem:ipsum
dola:meru
caby:cemu
$ pattern="lorem"
$ word="meru"
$ sed "/^$pattern:/ s/:.*/:$word/" inputfile
lorem:meru
dola:meru
caby:cemu
Upvotes: 2