我有一個文字文件,其中包含一些與此類似的內容:
# 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
這只是一個簡單的例子。它不執行任何錯誤檢查,並且在輸出重定向之一擦除原始檔案並留下空檔案的情況下,它不會備份原始檔案。我的意思是,不要在生產中使用它,但它會給你和如何做你想做的事情的想法。