how to insert texts in a file by using shell?
Hi,
I'm using fedora 14...i would like to insert few texts to a file in shell prompt(may be useful in scripting for in the future)...for eg, [root@ruby ~]# cat > hello 1 2 2 3 4 5 6 7 8 9 10 [root@ruby ~]# so in the above file i need to add the line "new line added" near the number 4 in the above file hello.....how can be this done ...? Thanks in advance.... |
the word 'near' is very vague; a lot of questions will arise like:
- near where? above? bottom? - why number 4? is it because you want to add it to every 4th line? or each time it sees the number "4"? - etc. |
Using sed you can do:
Code:
sed '/4/s/$/ new line added/' file Instead, if you want to add a new line before, use: Code:
sed '/4/i new line added' file Code:
sed '/4/a new line added' file |
Duplicate thread reported. Original is http://www.linuxquestions.org/questi...-shell-858721/. Better to keep all replies in original until moderators can merge the threads.
|
Quote:
|
Code:
ruby -ne 'print /^4/?$_+"insert text\n":$_' file |
Hi all,
First my reply to Chickenjoy---------->sorry for the incomplete information,i just want to add it below 4th line for this file only.And i think you need not be confused with other questions you have raised. Second to Mr.Coucix,--------->I've tried you suggestions but the entries are not permanent,I'll show it below, [root@ruby ~]$ sed '/4/i new line added/' hello 1 2 3 new line added/ 4 5 6 7 8 9 10 5:hekkpo [root@ruby ~]$ sed '/4/s/$/ new line added/' hello 1 2 3 4 new line added 5 6 7 8 9 10 5:hekkpo [root@ruby ~]$ cat hello 1 2 3 4 5 6 7 8 9 10 5:hekkpo [root@ruby ~]$ Third to Mr.Kurumi--------->I'll show the output [root@ruby ~]$ ruby -ne 'print /^4/?$_+"insert text\n":$_' hello bash: ruby: command not found [root@ruby ~]$ Thanks my friends for your suggestions till now, |
Sorry but it is not clear if you want to add some text below the 4th line or below the line containing the number 4 (which is the 5th line in your first example).
In the first case you can tell sed to apply the 'a' command to the 4th line only: Code:
sed '4a new line added' file Code:
sed '/4/a new line added' file |
Thanks Colucix
Hi,
It is working for me now Thanks a lot.... |
All times are GMT -5. The time now is 02:26 PM. |