Set variables a and b to the lines that you want to do the substitution on and then run awk:
a=1; b=5; awk '{ if (NR=='"$a"' || NR=='"$b"') sub("d_int","d_INT",$0); print $0}' 1.txt
In the above, awk checks to see if we are on line number $a
or on line number $b
. If so, it performs the substitution.
Part of the trick of using awk
is to protect the awk
commands from the shell. To do this, the awk
commands are in single quotes everywhere except where we explicitly want the shell to substitute in for $a
and $b
. $a
and $b
are each in double-quotes.
On your sample 1.txt
, the above produces:
INTEGER-d_INT ()
INTEGER-d_int ()
INTEGER-d_int ( )
INTEGER-d_intClass()
INTEGER-d_INTClass new()
Alternative Approach
sed
can also be used for this. The sed command for changing only line 1 is 1 s/d_int/d_INT/
and the sed
command for changing only line 5 is 5 s/d_int/d_INT/
. Thus, using shell substitution, a sed
program to do the substitutions on lines a
and b
is:
a=1; b=5; s='s/d_int/d_INT/' ; sed "$a $s; $b $s" 1.txt
Extension to an arbitrary number of lines
Suppose that we are supplied with an arbitrary list of lines
on which to apply the substitution:
lines="1 5 6 9 15 19 20"
s='s/d_int/d_INT/'
for line in $lines
do
echo line=$line
cmd="$line $s; $cmd"
done
echo cmd=$cmd
sed "$cmd" 1.txt