![](/img/trans.png)
[英]Sed - Replace all occurrences of a string in the second last line of a file
[英]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.