0

I have a file 1.txt

INTEGER-d_int ()
INTEGER-d_int  ()
INTEGER-d_int       (    )
INTEGER-d_intClass()
INTEGER-d_intClass     new()

and I want to replace the occurrence of d_int with d_INT on the lines 1 and 5.

In my case these line numbers are in a variable.

2
  • Since you tagged this with awk, is this the only possibility? What have you already tried?
    – slhck
    Feb 19, 2014 at 7:07
  • I not sure whether it will work in awk . I want result can use any command
    – Timson
    Feb 19, 2014 at 15:11

2 Answers 2

2

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
5
  • +1 also for the nice, clear explanation Feb 19, 2014 at 7:40
  • thanks.. I have a file or a variable which is having the line numbers and i want replace the words on that lines , is that possible?
    – Timson
    Feb 19, 2014 at 14:25
  • @Timson Probably. Let me know what your "file or variable" looks like.
    – John1024
    Feb 19, 2014 at 19:07
  • echo $lines - 1 5 6 9 15 19 20
    – Timson
    Feb 20, 2014 at 4:22
  • @Timson See updated answer.
    – John1024
    Feb 20, 2014 at 7:39
-1
sed -i '1,5s/d_int/d_INT/' 1.txt
3
  • Nope, this does not work. Also, you should probably explain one-liners a bit.
    – Olli
    Feb 20, 2014 at 10:30
  • It changes lines one through five
    – Ashtray
    Feb 20, 2014 at 10:45
  • Says -i:edit the file 1,5s:subst. in lines between 1 and 5, maybe I didn't understand what you wanted exactly..
    – seqizz
    Mar 7, 2014 at 10:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .