0

I have done this code to replace a specific line to a specific line using sed:

i=5

while (( i <= 10 ))
        do
                sed -i '$i s/.*/change/' file.txt
                ((i++))
        done

and this is the file.txt

1.  alloha
2.  this
3.  is
4.  just
5.  a
6.  test
7.  nonsense
8.  words
9.  at
10. all
11. as
12. you
13. can
14. see

and after I run the script, file.txt change to this :

1.  alloha
2.  this
3.  is
4.  just
5.  a
6.  test
7.  nonsense
8.  words
9.  at
10. all
11. as
12. you
13. can
14. s/.*/change/
15. s/.*/change/
16. s/.*/change/
17. s/.*/change/
18. s/.*/change/
19. s/.*/change/
20. see

I believe that sed command works fine because I test it in the command line and it works as I want, I think the problem is just from the i variable.

so anyone know how to make this works?

Holy semicolon
  • 868
  • 1
  • 11
  • 27

2 Answers2

0

After I searched a little bit, I found that I must use double quotes "" if I want to work with variables in sed command.

so instead of '' I replaced it with this "" as you can see in the following code :

i=5

while (( i <= 10 ))
do
    sed -i  "$i s/.*/change/" file.txt
    ((i++))
done

and now it works perfectly. for more details click here.

Holy semicolon
  • 868
  • 1
  • 11
  • 27
0

That seems to work for that simple use case but sed runs 5 times just to edit that file. Sed can do it in one invocation and does not involve looping while running sed 5 times!

sed -s '5,10s/\(^.*[[:space:]]\)*.*$/\1change/' file.txt
Jetchisel
  • 7,493
  • 2
  • 19
  • 18