Add couple new lines before the second pattern in file from shell script
Hi Friends,
I want to add couple lines before *pattern2 after *pattern1 in a text file from shell script. *pattern2 is being used for many times in the file. Appreciate for your kind help. See detail below: <Original file> *pattern0 x *pattern2 *pattern1 original lines *pattern2 <New file after modification> *pattern0 x *pattern2 *pattern1 original lines new line1 new line2 *pattern2 Thank you for your help, Jim |
1) Please use [code][/code] tags around your code, to preserve formatting and to improve readability.
2) It's generally better to provide real-life examples of the text to be modified than simplified mock-up versions. Are there any reserved characters in the text we may have to account for, for example? Also, how big is the file? What is its source? It's faster and easier to devise useful solutions when we know exactly what we're dealing with. 3) For the same reason you should also tell us about all the possible variations in the text patterns to match. Can pattern1 also appear more than once, for example? Or appear alone without pattern2 appearing? Can the pattern1..pattern2 block appear more than once? What do you want to happen in any of these cases? The main tools used for text manipulation are sed and awk. Assuming the above simple case is representative, then sed can do it: Code:
sed '/pattern1/,/pattern2/ { /pattern2/i new line1\nnew line2 Here are a few useful sed and awk references. http://www.grymoire.com/Unix/Sed.html http://sed.sourceforge.net/sedfaq.html http://sed.sourceforge.net/sed1line.txt http://www.grymoire.com/Unix/Awk.html http://www.gnu.org/software/gawk/man...ode/index.html http://www.informatik.uni-hamburg.de.../gawk_toc.html http://www.pement.org/awk/awk1line.txt http://www.catonmat.net/blog/awk-one...ined-part-one/ |
Thanks for help. I got an error.
# sed '/pattern1/,/pattern2/ {/pattern2/i NEWLINE1\nNEWLINE2}' testfile sed: -e expression #1, char 0: unmatched `{' |
1) I told you to use code tags.
2) I told you that you need to use a literal newline after the inserted text. |
Sorry, I don't understand what you say. I have not integrated it into script yet. I got that error when I ran it from command line. I think it should be able to run from command line, am I right? Can you please provide a complete sed command for this solution? pattern1 only shows up once in my file. Thank you.
|
The sed command must be broken up onto two separate lines, exactly as I posted it.
If there's anything after the text to be inserted, it must be put on a new line. |
How can I test this from Linux command line?
|
Works, thanks!!!!!!
|
All times are GMT -5. The time now is 05:49 AM. |