Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed replace second last line of file

Tags:

regex

linux

sed

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

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

I want to replace }}, with }} in short i want to remove , comma but this file has many other codes so i can't use pattern match i need to use second line from end of file.

like image 890
Satish Avatar asked Nov 28 '22 15:11

Satish


1 Answers

The following should work (note that on some systems you may need to remove all of the 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 the 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" )
}}
)
like image 189
Andrew Clark Avatar answered Dec 05 '22 15:12

Andrew Clark