How to insert string at particular 4th line in text file

I just want to add a particular string in text file using shell script

text file format

1 columns-10
2 text=89
3 no<>
4
5 test-9876
6 size=9

string need to insert in 4th line
<switch IP='158.195.2.567' port='5900' user='testc' password='asdfrp' Code='8'>

After inserting the output of file looks like

1 columns-10
2 text=89
3 no<>
4 <switch IP='158.195.2.567' port='5900' user='testc' password='asdfrp' Code='8'>
5 test-9876
6 size=9

Please suggest..

To keep the forums high quality for all users, please take the time to format your posts correctly.

First of all, use Code Tags when you post any code or data samples so others can easily read your code. You can easily do this by highlighting your code and then clicking on the # in the editing menu. (You can also type code tags

```text
 and 
```

by hand.)

Second, avoid adding color or different fonts and font size to your posts. Selective use of color to highlight a single word or phrase can be useful at times, but using color, in general, makes the forums harder to read, especially bright colors like red.

Third, be careful when you cut-and-paste, edit any odd characters and make sure all links are working property.

Thank You.

The UNIX and Linux Forums

****************************************************

$> STRING="<switch IP='158.195.2.567' port='5900' user='testc' password='asdfrp' Code='8'>"
$> awk -v string="${STRING}" 'NR == 4 {print string} $0' infile
columns-10
text=89
no<>
<switch IP='158.195.2.567' port='5900' user='testc' password='asdfrp' Code='8'>
test-9876
size=9
awk '
NR == 4 { $0="<switch IP='158.195.2.567' port='5900' user='testc' password='asdfrp' Code='8'>" 
            }
            { print $0 }  
' textfile

@kshji
This way the single quotes ' are gone. Had the same problem in my pre-edited solution.

It's still not working.. As there already a blank line in 4th position

Error I am getting : awk: can't set $0
record number 4

Which solution did you try out? I edited mine meanwhile.

Straight forward I am executing the below scripts but it is generating the below error

STRING="<switch IP='158.195.2.567' port='5900' user='testc' password='asdfrp' Code='8'>"

awk -v string="${STRING}" 'NR == 4 {print string} $0' test_file

awk: syntax error near line 1
awk: bailing out near line 1

. Life is learning process. Awk has ... method to handle " '. zaxxon has solution for that.

awk -v line4="<switch IP='158.195.2.567' port='5900' user='testc' password='asdfrp' Code='8'>" '
NR == 4 {
             print line4 ; next
            }
            { print $0 }
' infile

Or

awk -v line4="<switch IP='158.195.2.567' port='5900' user='testc' password='asdfrp' Code='8'>" '
NR == 4 {
             $0=line4
            }
            { print $0 }
' infile

Works fine. Tested.

You awk may not support -v option
try nawk,gawk