Hi I need help with writing a script to change a string in a file.
The script needs to read an input list (list.txt) file line by line searching for that string in a text.file. Once the string is found the last few words in the string should be replaced.
eg list.txt will contain
hello my name is dave
hello our name is dave
text.file will contain data such as
hello my name is dave
hello mikes name is really dave
hello our name is dave
hello we are dave
once the string is matched it should be changed to :
hello my name is irrelevant now
The text.file should end up as follows if the script has worked:-
hello my name is irrelevant now
hello mikes name is really dave
hello our name is irrelevant now
hello we are dave
Indeed i've tried to do this using a for loop and sed but not sure if this is the best way of achieving this as i'll need another list for the replacement variable:-
for i in `cat text.file`
do
sed "s/\$i/$var1" text.file > text.file.new
awk 'NR==FNR {T[$0];next} $0 in T {sub (/ [^ ]*$/, " irrelevant now")}1' file1 file2
hello my name is irrelevant now
hello mikes name is really dave
hello our name is irrelevant now
hello we are dave
Sorry, but this question reeks like homework so much i have to close it.
@thread-op:
Your solution:
for i in `cat text.file`
do
sed "s/\$i/$var1" text.file > text.file.new
has two shortcomings:
first, the sed-statement is incomplete and should read:
"s/\$i/$var1/"
Notice the "/" at the end. Second, your for-loop is not closed:
for <var> in <list of values>
do
cmd1
cmd2
...
done
You might want to correct these and then look what your code produces and if it matches what you want. Chances are there are still differences.
Btw., using "for"-loops with open-ended lists (you do not know beforehand how long text.file will be) is never a good idea, though not syntactically wrong. Better replace such constructs with a "while"-loop, which will do the same:
while read <var> ; do
cmd1 "$VAR"
cmd2 "$VAR"
....
done < /path/to/input.file