A GNU sed solution that does not require a full read of the entire file:
sed '/^\t#$/ {n;/^\tpap$/a\\tpython'$'\n''}' file
/^\t#$/ matches the lines for comment only (exactly \t# exactly), and in this case (only) the whole expression {...} is executed:n loads and prints the next line./^\tpap/ exactly matches the next line \tpap .- if it matches,
a\\tpython will output \n\tpython before the next line reading - note that the line of the attached line ( $'\n' ) is required to signal the end of the text passed to a (you can alternatively use several -e options )
(Aside: with BSD sed (OS X) it gets cumbersome because
- Control characters. such as
\n and \t not supported directly and must be spliced ββin the form of literals quoted by ANSI C. Leading spaces are invariably removed from the text argument to the a command, so the substitution approach should be used: s//&\'$'\n\t'python'/ replaces the pap string with itself plus the string to add:
sed '/^'$'\t''#$/ {n; /^'$'\t''pap$/ s//&\'$'\n\t'python'/;}' file
)
awk solution (POSIX compatible), which also does not require a full read of the entire file:
awk '{print} /^\t#$/ {f=1;next} f && /^\tpap$/ {print "\tpython"} {f=0}' file
{print} : prints each line of input/^\t#$/ {f=1;next} : sets the flag f (for 'found') to 1 if only the comment line is found (matching \t# ) and goes to the next line.f && /^\tpap$/ {print "\tpython"} : if the line is preceded by a comment line and exactly matches \tpap , an additional line \tpython .{f=0} : resets the flag indicating the line for comment only.
source share