我有一个文本文件,其中包含一些与此类似的内容:
# General information about the project.
project = u'Py6S'
copyright = u'2012, Robin Wilson'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.5'
# The full version, including alpha/beta/rc tags.
release = '0.5'
我想将该version = '0.5'
行替换为version = X
其中 X 是给予脚本的命令行参数,然后对该release =
行执行相同的操作。
我可以调用一个简单的命令来进行这种替换吗?我已经研究了sed
一下,但似乎 sed 中的全局替换需要我搜索version = '0.5'
,但我真正想要搜索的是以 - 开头的行version =
,因为我不知道当我时版本可能是什么运行脚本!
有任何想法吗?
答案1
sed -i "/^version =/s/'[^']*'/'NEW_VERSION_IS_HERE'/" your_file
答案2
一种使用方法perl
:
假设infile
有您粘贴在问题中的内容。
内容script.pl
:
use warnings;
use strict;
use Getopt::Long;
## Check arguments.
die qq[Usage: perl $0 <file> [--version=<num>] [--release=<num>]\n] unless @ARGV > 1;
my ($version, $release);
## Get value of arguments.
GetOptions(
q[version=f] => \$version,
q[release=f] => \$release,
) or die qq[ERROR: Bad input arguments\n];
## Sanity check.
exit 0 if ! defined $version && ! defined $release;
## Read input file line by line, and substitute values of 'version' and 'release'
## when matched.
while ( <> ) {
chomp;
s/\A((?i:version)\s*=\s*')([^']+)(?=')/$1 . (defined $version ? $version : $2)/e;
s/\A((?i:release)\s*=\s*')([^']+)(?=')/$1 . (defined $release ? $release : $2)/e;
printf qq[%s\n], $_;
}
像这样运行它:
perl script.pl infile --version=1.3 --release=2.6
具有以下输出:
# General information about the project.
project = u'Py6S'
copyright = u'2012, Robin Wilson'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.3'
# The full version, including alpha/beta/rc tags.
release = '2.6'
答案3
如果$X
是存储新版本的参数,
ed file << EOF
g/^version =/s/.*/version = '$X'/
g/^release =/s/.*/release = '$X'/
w
q
EOF
这假设$X
有一个合理的值,例如1.2.3-foo
,并且没有命令解释器特有的字符ed
。
答案4
作为 shell 脚本:
#!/bin/ksh
function usage {
echo
echo "Usage: $0 <file> <version> <release>"
echo
exit 1
}
function update_version {
cat $file | sed -e "s/^version.*$/version = \'$version\'/" > $file.new
mv $file.new $file
}
function update_release {
cat $file | sed -e "s/^release.*$/release = \'$release\'/" > $file.new
mv $file.new $file
}
file=$1
version=$2
release=$3
if [ ! -f $file ]; then
usage
fi
if [ $# != 3 ]; then
usage
fi
update_version
update_release
这只是一个简单的例子。它不执行任何错误检查,并且在输出重定向之一擦除原始文件并留下空文件的情况下,它不会备份原始文件。我的意思是,不要在生产中使用它,但它会给你和如何做你想做的事情的想法。