Copy the contents of a file to another file at a point relative to the end of the file

New to StackExchange, I'm sorry for the mistakes.

I have an input file that needs to be copied to another file, before the last character.

 

inputfile.txt:

input {
       "inputstuff"
}

filetowriteto.txt:

Stuff {
       foo {
            "foostuff"
       }
       bar {
            "barstuff"
       }
}

 

After running the script, the resulting file should now be:

filetowriteto.txt:

Stuff {
       foo {
            "foostuff"
       }
       bar {
            "barstuff"
       }
       input {
              "inputstuff"
       }
}

 

Basically script copies the set of rows inputand inserts them directly before the last right parenthesis in filetowriteto.txt.

The script cannot count on the number of lines, because it filetowriteto.txtdoes not have the predictive number of lines foo or bar, and I do not know how to use sed or awk for this.

+4
source share
3 answers

Try:

$ awk 'FNR==NR{ if (NR>1) print last; last=$0; next} {print "       " $0} END{print last}' filetowriteto.txt inputfile.txt 
Stuff {
       foo {
            "foostuff"
       }
       bar {
            "barstuff"
       }
       input {
              "inputstuff"
       }
}

:

awk 'FNR==NR{ if (NR>1) print last; last=$0; next} {print "       " $0} END{print last}' filetowriteto.txt inputfile.txt >tmp && mv tmp filetowriteto.txt

  • FNR==NR{ if (NR>1) print last; last=$0; next}

    (), , last, (b) last (c) next.

    awk. FNR==NR , . , awk NR - , , FNR - , . , FNR==NR , .

  • print " " $0

    .

  • END{print last}

    , , .

+2

:

$ cat /tmp/f1.txt
input {
       "inputstuff"
}
$ cat /tmp/f2.txt
Stuff {
       foo {
            "foostuff"
       }
       bar {
            "barstuff"
       }
}

:

$ ( sed '$d' f2.txt ; cat f1.txt ; tail -n1 f2.txt ) 

( )

$ { sed '$d' f2.txt ; cat f1.txt ; tail -n1 f2.txt; } 

?

  • sed '$d' f2.txt , f2.txt

  • cat f1.txt f1.txt

  • tail -n1 f2.txt f2

f1.txt, sed cat. sed :

$ { sed '$d' /tmp/f2.txt ; sed 's/^/       /' /tmp/f1.txt ; sed -n '$p' /tmp/f2.txt;  } 
Stuff {
       foo {
            "foostuff"
       }
       bar {
            "barstuff"
       }
       input {
              "inputstuff"
       }
}

, , >.

+2
$ cat tst.awk
NR==FNR {
    rec = (NR>1 ? rec ORS : "") $0
    next
}
FNR>1 {
    print prev
    if ( sub(/[^[:space:]].*/,"",prev) ) {
        indent = prev
    }
}
{ prev=$0 }
END {
    gsub(ORS,ORS indent,rec)
    print indent rec ORS prev
}

$ awk -f tst.awk inputfile.txt filetowriteto.txt
Stuff {
       foo {
            "foostuff"
       }
       bar {
            "barstuff"
       }
       input {
              "inputstuff"
       }
}

, , , .

+1

Source: https://habr.com/ru/post/1657693/


All Articles