Shell 无法使用脚本递增文件中声明的变量的最后2位
我的档案如下:Shell 无法使用脚本递增文件中声明的变量的最后2位,shell,unix,Shell,Unix,我的档案如下: elix554bx.xayybol.42> vi setup.REVISION # Revision information setenv RSTATE R24C01 setenv CREVISION X3 exit 我的要求是从文件中读取RSTATE,然后增加setup.REVISION文件中RSTATE的最后2位数字,并覆盖到同一个文件中。 您可以建议如何执行此操作吗?如果您使用的是vim,则可以使用以下顺序: /RSTATE/ $<C-a>:x /RS
elix554bx.xayybol.42> vi setup.REVISION
# Revision information
setenv RSTATE R24C01
setenv CREVISION X3
exit
我的要求是从文件中读取RSTATE,然后增加setup.REVISION文件中RSTATE的最后2位数字,并覆盖到同一个文件中。
您可以建议如何执行此操作吗?如果您使用的是
vim
,则可以使用以下顺序:
/RSTATE/
$<C-a>:x
/RSTATE/
$:x
第一行后面是一个返回,搜索RSTATE。第二行跳转到行的末尾,并使用Control-a(如上所示,以及在vim
文档中)增加数字。如果要增加数字,请重复多次。:x
后面还有一个返回值并保存文件
唯一棘手的是,数字的前导0使vim
认为数字是八进制的,而不是十进制的。您可以通过使用:set nrformats=
然后使用return关闭八进制和十六进制来覆盖它;默认值为nrformats=octal,hex
你可以从Drew Neil的书中学到很多关于vim的知识。这些信息来自第二章的技巧10。我为你写了一节课
class Reader
{
public string ReadRs(string fileWithPath)
{
string keyword = "RSTATE";
string rs = "";
if(File.Exists(fileWithPath))
{
StreamReader reader = File.OpenText(fileWithPath);
try
{
string line = "";
bool finded = false;
while (reader != null && !finded)
{
line = reader.ReadLine();
if (line.Contains(keyword))
{
finded = true;
}
}
int index = line.IndexOf(keyword);
rs = line.Substring(index + keyword.Length +1, line.Length - 1 - (index + keyword.Length));
}
catch (IOException)
{
//Error
}
finally
{
reader.Close();
}
}
return rs;
}
public int GetLastTwoDigits(string rsState)
{
int digits = -1;
try
{
int length = rsState.Length;
//Get the last two digits of the rsstate
digits = Int32.Parse(rsState.Substring(length - 2, 2));
}
catch (FormatException)
{
//Format Error
digits = -1;
}
return digits;
}
}
您可以使用现有的
Reader reader = new Reader();
string rsstate = reader.ReadRs("C://test.txt");
int digits = reader.GetLastTwoDigits(rsstate);
以下是一个
awk
one liner type解决方案:
awk '{
if ( $0 ~ 'RSTATE' ) {
match($0, "[0-9]+$" );
sub( "[0-9]+$",
sprintf( "%0"RLENGTH"d", substr($0, RSTART, RSTART+RLENGTH)+1 ),
$0 );
print; next;
} else { print };
}' setup.REVISION > tmp$$
mv tmp$$ setup.REVISION
返回:
setenv RSTATE R24C02
setenv CREVISION X3
exit
这将适当地处理从两位数到三位数到更多位数的转换。数字总是01还是代码需要处理00..99?如果最后三个字符是199呢?那会变成200、1100、100还是别的什么?说到这里,如果最后三个字符是C99呢?另外,您是在使用real
vi
,还是在伪装使用vim
?