Sed - insert line after double tab match for start of inserted line

I have the following input.txt:

        "loop:\n\t" 
        "add %%g1, 1, %%g1\n\t" 

      

and I want to insert a line between the first and second line to get:

    "loop:\n\t" 
    "add %%g1, 1, %%g1\n\t" 
    "add %%g1, 1, %%g1\n\t" 

      

Here's what I've tried:

sed '/loop\:/a "\t \t add %%g1, 1, %%g1\\n\\t"' input.txt

      

But with this I get:

        "loop:\n\t" 
"       add %%g1, 1, %%g1\n\t" 
        "add %%g1, 1, %%g1\n\t" 

      

As you can see, the first quote of the inserted line is at the beginning of the line, not just before the word add

.

How do I get around this problem?

thank

UPDATE 1:

I realized that the spaces between the beginning of each line and the first characters are not tables, but classic ones.

Then I tried to use this solution (from this link )

awk '{print} /loop\:/{ print substr($0,1,match($0,/[^[:space:]]/)-1) "add %%g1, 1, %%g1\n\t"}' input.txt

      

This command line seems to be calculating the right indentation from the previous line, but unfortunately I get with this:

           "loop:\n\t" 
"add %%g1, 1, %%g1\n\t" 
           "add %%g1, 1, %%g1\n\t" 

      

whereas I would like to have:

           "loop:\n\t" 
           "add %%g1, 1, %%g1\n\t" 
           "add %%g1, 1, %%g1\n\t" 

      

Can you see the error?

Hello

0


source to share


2 answers


sed are simple substitutions on separate lines, i.e. everything. For something even a little more interesting, just use awk for clarity, portability, efficiency, and most of the other desired software attributes:

$ awk '{print} /loop:/{print "\t\"add %%g1, 1, %%g1\\n\\t\""}' file
        "loop:\n\t"
        "add %%g1, 1, %%g1\n\t"
        "add %%g1, 1, %%g1\n\t"

      

The above just implements what you were trying to do with sed, but probably the best approach depends on your actual requirements, eg. any of them has advantages over the above, but gives the same result under different conditions:



$ awk '1;NR==2' file
        "loop:\n\t"
        "add %%g1, 1, %%g1\n\t"
        "add %%g1, 1, %%g1\n\t"


$ awk '{print} f{print;f=0} /loop:/{f=1}' file
        "loop:\n\t"
        "add %%g1, 1, %%g1\n\t"
        "add %%g1, 1, %%g1\n\t"

$ awk '{print} /loop:/{sub(/".*/,""); print $0 "\"add %%g1, 1, %%g1\\n\\t\""}' file
        "loop:\n\t"
        "add %%g1, 1, %%g1\n\t"
        "add %%g1, 1, %%g1\n\t"

      

Based on the comment you left in a previous answer to my question , it sounds like you want one of these bottom so you don't need to indent.

+1


source


With GNU sed:

Escape first \t

with a backslash:

sed '/loop\:/a \\t "add %%g1, 1, %%g1\\n\\t"' file

      



or search and replace:

sed 's/loop\:.*/&\n\t "add %%g1, 1, %%g1\\n\\t"/' file

      

+1


source







All Articles