Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write to line 10?

Tags:

shell

sed

awk

perl

I need a script that can write text to an exsisting file starting on line 10. It is a blank line so it wont be a find / replace. Would like preferably it to be in bash, but anything that the terminal can interpret will work just fine.

RE-EDITED:

Sorry but still having a bit of a problem after I tested... Think it has something to do with what I want write to a file. Maybe this will make it easier..

  3 c
  4 d
  5 e
  6 f
  7 g
  8 h
  9 i
 10      zone "$zone" in {
 12          type master;
 13          file "/etc/bind/db.$zone";
 14   };
 15 k
 16 l
 17 m

Thanks in Advance, Joe

like image 737
jmituzas Avatar asked Dec 12 '22 16:12

jmituzas


1 Answers

Using sed:

sed -i -e '10a\
new stuff' file

Using bash:

IFS=$'\n'
i=0
while read -r line; do
    i=$((i+1))
    if test $i -eq 10; then
        echo "new stuff"
    else
        echo "$line"
    fi
done <file >file.tmp
mv file.tmp file

Note that I'm not really sure if you mean insert at line 10 or at line 11, so double check the places I wrote 10 above. You might want 9 for the sed command or 11 for the bash version.

In perl, you can use the $NR variable.

open FILEHANDLE, "<file";
while (<FILEHANDLE>) {
    if ($NR == 10) {
        # do something
    }
}

And in awk, it's NR.

awk 'NR != 10 { print }
NR == 10 { print "Something else" }' file

But note that you can find and replace a blank line, e.g.

sed -i -e 's/^$/replacement text/' file
like image 144
Mikel Avatar answered Jan 05 '23 23:01

Mikel