How to write in line 10?

I need a script that can write text to an existing file starting at line 10. This is an empty line, so it will not find / replace. It is advisable that this be in bash, but anything the terminal can interpret will work fine.

RE-EDITED: 

Sorry, but still a bit of a problem after I tested ... I think this has something to do with what I want to write to the file. Perhaps it will simplify.

  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 Advance, Joe

+4
source share
6 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 

Please note: I'm not sure if you mean the insert on line 10 or line 11, so double check the places I wrote 10 above. You may need 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 , he's NR .

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

But note that you can find and replace an empty string, for example

 sed -i -e 's/^$/replacement text/' file 
+8
source

You can simply do:

 head -10 fileA > fileB; echo "new text" >> fileB; 

Please note that this happens much faster than when using sed

+2
source

With sed:

 sed '10 s/^/text' file >file.new && mv file.new file 

With gnu-sed:

 sed -i '10 s/^/text' file 

With awk:

 awk 'NR==10 {$0="text"} 1' file >filen.new && mv file.new file 
+2
source
 sed 10cFoobar foo 

replaces line 10 with "Foobar". This may contain line breaks:

 sed 4cFoobar"\nFoobar" foo 

This contradicts Mikel's decision, which he used instead of c. The difference is that it is being replaced, another is being added.

+1
source

If the file already has 9 lines, the shell would be easy;)

 $ echo "I am line 10" >> file-with-9-lines.txt 

If a file can contain less than 9 lines or even more (and you still want to write to line 10), perl modul Tie :: File will make things very simple:

 #!/usr/bin/perl use Tie::File; tie my @file, 'Tie::File', '/path/to/some/file' or die $!; $file[9] = "I am the content of line 10"; 
0
source

Ruby (1.9 +)

 $ ruby -i.backup -ne 'print ($.==10)?"word\n":$_' file 
0
source

Source: https://habr.com/ru/post/1338347/


All Articles