Insert line using sed or awk at line using line number as variable
Hello All,
I want to insert a line at a particular line number using sed or awk. where line number is not fixed and is in form of variable. I want to use variable in sed or awk command. I tried something like below, but no luck. line=10 sed '$linei\newline' file |
Try changing the single quotes to double and see how you go.
|
Getting error
$ sed "$linei\abcd" 1.conf sed: 1: "\abcd": unterminated regular expression |
Getting error
$ sed "$linei\abcd" 1.conf sed: 1: "\abcd": unterminated regular expression |
I prefer to use awk for this, since then I don't need to worry about escaping:
Code:
awk -v "n=line-number" -v "s=line to insert" '(NR==n) { print s } 1' input-file This second variant will append the line, if the line number is larger than the number of lines in the file. It will not add empty lines, though; just the line to be inserted: Code:
awk -v "n=line-number" -v "s=line to insert" ' Code:
#!/bin/sh |
Quote:
which sed version are you using? This should work with GNU sed: Code:
sed "${line} i abcd" 1.conf |
Great !! thanks so much Guys ..
This worked sed "${line} i abcd" 1.conf |
If you are not sure why it worked? It is because your previous invocation had it looking for a variable called $linei
and then passing \a which sed does not understand as an escape character. |
New last line
All,
Seeing the code here, what method is used to count all the lines in a current file and put the new line at X+1? I particular I need a script to add lines to my "sources.list" repositories file, when configuring new servers. Thanks! OMR |
You want to append lines ? Try:
Code:
echo "New line appended" >> sources.list |
Replacing existing lines
All,
OK the "echo "string" >> "path/to/file" works, but got a couple where I need SED or AWK to rewrite the existing lines, What is correct syntax for that? Thanks! OMR |
Since you seem to want to learn how to do more, it's time for you to start studying up on the tools you want to use.
Here are a few useful sed references. http://www.grymoire.com/Unix/Sed.html http://sed.sourceforge.net/grabbag/ http://sed.sourceforge.net/sedfaq.html http://sed.sourceforge.net/sed1line.txt Here are a few useful awk references: http://www.grymoire.com/Unix/Awk.html http://www.gnu.org/software/gawk/man...ode/index.html http://www.pement.org/awk/awk1line.txt http://www.catonmat.net/blog/awk-one...ined-part-one/ A couple of regular expressions tutorials: http://mywiki.wooledge.org/RegularExpression http://www.grymoire.com/Unix/Regular.html |
All times are GMT -5. The time now is 07:03 AM. |