bash - Replacing a line from multiple files, limiting to a line number range -
i have large number of files , want replace lines of these files. don't know exact contents of lines, know of them contain 2 known words - let's example 'programmer' , 'bob'. lines want replace like:
created programmer bob programmer extraordinaire bob, such awesome guy copyright programmer bob, rights reserved
so far sounds easy, problem want replace lines contained within line range - example in beginning of file (where typically 1 find comments regarding file). can't replace lines found in later parts of file, because don't want accidentally replace actual code.
so far have tried:
find . -exec grep -il -e 'programmer.*bob' {} \; | xargs sed -i '1,10 /programmer.*bob/ic\line replaced'
(i'm using find because grep ran infinite recursion - think. not point here.)
however seems can't use address ranges c\ (change line). feel free point out syntax errors, think i've tried no avail. work without line numbers.
edit: got answer, decided edit question include solution expands upon answer got - maybe find helpful.
i realised later want retain possible whitespace , comment characters in beginning of line. accomplished using command:
find . -exec grep -ili '.*programmer.*bob.*' {} \; xargs sed -i -r '1,10 s/([ \t#*]*)(.*programmer.*bob.*)/\1line replaced/i'
\1 keeps pattern matches [ \t#*]*. 1 change ^[ \t#*]* anchor pattern beginning of line, (i think) current version change
** text don't want remove ** programmer bob
into
** text don't want remove ** line replaced
which better. (i added -i (capital i) flag find command, skips binary files.)
you mixing addresses , commands. simple substitution should work:
find . -exec grep -il -e 'programmer.*bob' {} \; \ | xargs sed -i '1,10 s/.*programmer.*bob.*/line replaced/'
Comments
Post a Comment