I have a file which requires modification via a shell script.
Need to do the following: 0. take input from user for new text. 1. search for a keyword in the file. 2. replace the line next to this to this keyword with user supplied input.
for e.g., my file has the following text:
(some text)
(some text)
(text_to_search)
(text_to_replace)
(some text)
(some text)
(some text)
I need to search the file for and rewrite the file replace the line with the input to this script leaving the remaining content untouched.
Regards
RudiC
April 26, 2013, 2:00am
2
This is an utterly terse specification. What have you tried so far?
BTW, I think there are many threads on this question, did you search these forum?
I did search but was not able to find a specific solution.
awk ' zap==1 {print "user input"; zap=0; next} /my pattern/ {zap=1; print $0; next} {print $0} ' infile > newfile
but issue comes when i try taking an input from user.
awk ' zap==1 {print $1; zap=0; next} /my pattern/ {zap=1; print $0; next} {print $0} ' infile > newfile
i get $1 in my file.
Here is one way to do it:
$ cat input
123456
123456
trigger_to_replace_next_line
text_to_replace
678905
678905
$ cat test.sh
# usage trigger replacement
awk '$0 ~ /trigger/ {print; getline; print replacement; next} {print} ' trigger="$1" replacement="$2" input
$ ./test.sh trigger_to_replace_next_line "replacement text"
123456
123456
trigger_to_replace_next_line
replacement text
678905
678905
Thanks Hanson. That solved it beautifully.
Great! Thanks for posting the problem.
Hi Hanson,
What if i have to replace the line 2 or 3 lines after the match?
Regards
RudiC
June 27, 2013, 2:55pm
8
Try
awk '/text_to_search/{L=NR+lines} NR==L {getline < "-"; L=0}1' lines=2 file