1

I need to insert some lines of code into a file. The problem is, I want to insert it after some function calling AND after the semicolon behind it, too.

I'd like to achieve this just with sed, but I don't know why.


Example:

Source code snippet:

10 printf("asdf");
11
12 myFunc()
13
14 ;

Here I want to insert the snippet behind the myFunc() call, but I can't insert it directly to the line 13, but to the line 15.

Desired code after insertion:

10 printf("asdf");
11
12 myFunc()
13
14 ;
15 SNIPPET

My best attempt is this:

sed -e '13 i\SNIPPET'

Which obviously doesn't "wait" for the semicolon.

So, is there any way I could combine those conditions, so I'd insert my code snippet after the first semicolon after the line number ***?

  • 1
    Please add sample output for that sample input to your question. – Cyrus Dec 11 '15 at 15:08
  • 1
    sed is good for manipulating text lines, if you want to do something else it's probably a good idea to use awk, it's a bit more feature-rich. – MatthewRock Dec 11 '15 at 15:14
0

I wouldn't use sed - I don't think it's a good tool for this purpose, due to it's inherent line-oriented nature.

I would instead suggest:

#!/usr/bin/env perl
use strict;
use warnings;

while (<>) {
    #print current line (because we insert _after) 
    print;
    #extract the number. If you need to work on _actual_ line number, you need $.
    my ($num) = m/^(\d+)/;
    if ( $num > 13 and m/;/ ) {
        #print snippet, bail out
        print ++$num, " SNIPPET\n";    
        last;
    }
}
#print rest of file
print <>;

Note - this extracts the numbering from the content, based on your example. I couldn't quite tell if you wanted actual line numbers - although sed -e '13 ..' implies that you do.

In which case:

if ( $. > 13 and m/;/ ) {
    print "SNIPPET\n"; 
    last;
}
2

How about:

sed '
  /myFunc()/!b
  :1 
  s/;/; SNIPPET/;t
  n;b1'

Or for line 13:

sed '
  13!b
  :1 
  s/;/; SNIPPET/;t
  n;b1'
  • The second one looks exactly like what I need - could you please add a little description? I'd like to understand what is it doing exactly. – Eenoku Dec 11 '15 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.