簡體   English   中英

sed替換文件的第二行

[英]sed replace second last line of file

我想替換文件的第二行,我知道$ use用於最后一行,但不知道怎么說最后一行。

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

我想替換}},}}簡而言之我想刪除,逗號,但這個文件有很多其他代碼所以我不能使用模式匹配我需要使用文件末尾的第二行。

如果你知道,如何改變第N行,只需先反轉文件,例如它不像其他sed解決方案那么專業,但是有效... :)

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

例如,從下一個輸入

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

以上所作

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

tail -r是Linux的tac命令的BSD等價物。 在Linux上使用OS X或Freebsd上的tac使用tail -r Bot做同樣的事情:按行的順序打印文件(最后一行打印為第一行)。

反轉文件,在第二行上工作,然后重新反轉文件:

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

要將結果保存回“文件”,請將其添加到命令中

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

或者,使用ed腳本

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

以下內容應該有效(請注意,在某些系統上,您可能需要刪除所有注釋):

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' 

或者緊湊版:

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

例:

$ 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" )
}}
)

這可能適合你(GNU sed):

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

在模式空間中保留兩行,並在文件末尾替換所需的模式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM