Sed replace the second last line of the file

I want to replace the second last line of the file, I know what to use $ last for the last line, but I don’t know how to say the second line from the end.

parallel ( { ignore(FAILURE) { build( "Build2Test", BUILDFILE: "", WARFILE: "http://maven.example.com/130602.0.war", STUDY: "UK", BUG: "33323" ) }}, ) 

I want to replace }}, with }} short one, I want to remove the comma , but there are many other codes in this file, so I can not use pattern matching. I need to use the second line from the end of the file.

+4
source share
4 answers

The following should work (note that on some systems you may need to delete all comments):

 sed '1 { # if this is the first line h # copy to hold space d # delete pattern space and return to start } /^}},$/ { # if this line matches regex /^}},$/ x # exchange pattern and hold space b # print pattern space and return to start } H # append line to hold space $ { # if this is the last line x # exchange pattern and hold space s/^}},/}}/ # replace "}}," at start of pattern space with "}}" b # print pattern space and return to start } d # delete pattern space and return to start' 

Or compact version:

 sed '1{h;d};/^}},$/{x;b};H;${x;s/^}},/}}/;b};d' 

Example:

 $ echo 'parallel ( { ignore(FAILURE) { build( "Build2Test", BUILDFILE: "", WARFILE: "http://maven.example.com/130602.0.war", STUDY: "UK", BUG: "33323" ) }}, )' | sed '1{h;d};/^}},$/{x;b};H;${x;s/^}},/}}/;b};d' parallel ( { ignore(FAILURE) { build( "Build2Test", BUILDFILE: "", WARFILE: "http://maven.example.com/130602.0.war", STUDY: "UK", BUG: "33323" ) }} ) 
+6
source

If you know how to change the Nth line, just format the file first, for example. This is not as many professionals as other sed solutions, but it works ... :)

 tail -r <file | sed '2s/}},/}}/' | tail -r >newfile 

eg. from next input

 }}, }}, }}, }}, }}, 

the above does

 }}, }}, }}, }} }}, 

tail -r are the BSD equivalent of the Linux tac command. On Linux, use tac for OS X or Freebsd using tail -r . The bot does the same: it prints the file in the revered line order (the last line prints as the first).

+7
source

cancel the file, work with the second line, then flip the file:

 tac file | sed '2 s/,$//' | tac 

to save the result back to the "file", add it to the command

  > file.new && mv file file.bak && mv file.new file 

Or use ed script

 ed file <<END $-1 s/,$// w q END 
+5
source

This may work for you (GNU sed):

 sed '$!N;$s/}},/}}/;P;D' file 

Save two lines in the template space and at the end of the file, replace the required template.

+3
source

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


All Articles