Replace words on given line numbers

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.

Timson

Posted 2014-02-19T06:54:09.487

Reputation: 1

Since you tagged this with awk, is this the only possibility? What have you already tried? – slhck – 2014-02-19T07:07:14.123

I not sure whether it will work in awk . I want result can use any command – Timson – 2014-02-19T15:11:07.940

Answers

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

John1024

Posted 2014-02-19T06:54:09.487

Reputation: 13 893

+1 also for the nice, clear explanation – MariusMatutiae – 2014-02-19T07:40:12.190

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 – 2014-02-19T14:25:51.967

@Timson Probably. Let me know what your "file or variable" looks like. – John1024 – 2014-02-19T19:07:11.687

echo $lines - 1 5 6 9 15 19 20 – Timson – 2014-02-20T04:22:12.533

@Timson See updated answer. – John1024 – 2014-02-20T07:39:57.443

-1

sed -i '1,5s/d_int/d_INT/' 1.txt

seqizz

Posted 2014-02-19T06:54:09.487

Reputation: 81

Nope, this does not work. Also, you should probably explain one-liners a bit. – Olli – 2014-02-20T10:30:00.757

It changes lines one through five – Ashtray – 2014-02-20T10:45:45.920

Says -i:edit the file 1,5s:subst. in lines between 1 and 5, maybe I didn't understand what you wanted exactly.. – seqizz – 2014-03-07T10:06:30.107