Harsh Pratap Harsh Pratap - 3 months ago 10
Bash Question

search pattern between known string and unknown decimal number which are in diffrent line number

I want to search pattern between a known string and unknown decimal number which is in different line in a file.

Suppose we have to search a pattern and replace with another pattern in same file :

Ex. file contains below contents :

###line 1..
###line 2..
###line 3..
known_string
###line 5
###line 6
4444
###line 8
###line 9
###line 10
unknown_string
###line 11
###line 12
6666
unknown_string
###line 15
###line 16
5555
EOF


In the above example, I have to search a pattern from file.

known_string
###line 5
###line 6
4444


and have to replace with another pattern in same file :

known_string
###line 5
###line 6
8850


So, the output should be in below format :

###line 1..
###line 2..
###line 3..
known_string
###line 5
###line 6
8850
###line 8
###line 9
###line 10
unknown_string
###line 11
###line 12
6666
unknown_string
###line 15
###line 16
5555
EOF


I have tried using "sed" command,

sed -i -e '/known_sting/{p:d;};N;N;N;c; 'known_string'N;'8850'' filename


But not getting the desired result.

Thanks.

Answer

It is easier with awk:

awk '/^[ \t]*known_string/{p=1} p && $0+0==$0{$0="8850"; p=0} 1' file

###line 1..
###line 2..
###line 3..
known_string
###line 5
###line 6
8850
###line 8
###line 9
###line 10
unknown_string
###line 11
###line 12
6666
unknown_string
###line 15
###line 16
5555
EOF
  • /^known_string/{p=1} will set a flag when known_string is found at start.
  • $0+0==$0 check is to ensure current line is a valid number.
  • p=0 will reset the flag.