Jim*_*Jim 5 unix linux bash scripting
我需要通过脚本修改文件.
我需要执行以下操作:
如果特定字符串不存在,则将其附加.
所以我创建了以下脚本:
#!/bin/bash
if grep -q "SomeParameter A" "./theFile"; then
echo exist
else
echo doesNOTexist
echo "# Adding parameter" >> ./theFile
echo "SomeParameter A" >> ./theFile
fi
Run Code Online (Sandbox Code Playgroud)
这有效,但我需要做一些改进.
我认为如果检查"SomeParameter"是否存在然后查看它是否后跟"A"或"B"会更好.如果是"B"则将其设为"A".
否则在最后一个注释块开始之前附加字符串(就像我一样).
我怎么能这样做?
我不擅长编写脚本.
谢谢!
首先,更改任何SomeParameter已存在的行.这应该适用于像SomeParameter或的行SomeParameter B,以及任意数量的额外空格:
sed -i -e 's/^ *SomeParameter\( \+B\)\? *$/SomeParameter A/' "./theFile"
Run Code Online (Sandbox Code Playgroud)
然后添加该行,如果它不存在:
if ! grep -qe "^SomeParameter A$" "./theFile"; then
echo "# Adding parameter" >> ./theFile
echo "SomeParameter A" >> ./theFile
fi
Run Code Online (Sandbox Code Playgroud)
Nah*_*eul -1
一个 Perl 单行代码
perl -i.BAK -pe 'if(/^SomeParameter/){s/B$/A/;$done=1}END{if(!$done){print"SomeParameter A\n"}} theFile
Run Code Online (Sandbox Code Playgroud)
将创建备份 theFile.BAK(-i 选项)。一个更详细的版本,考虑了最后的评论,有待测试。应保存在文本文件中并执行perl my_script.pl或chmod u+x my_script.pl ./my_script.pl
#!/usr/bin/perl
use strict;
use warnings;
my $done = 0;
my $lastBeforeComment;
my @content = ();
open my $f, "<", "theFile" or die "can't open for reading\n$!";
while (<$f>) {
my $line = $_;
if ($line =~ /^SomeParameter/) {
$line =~ s/B$/A/;
$done = 1;
}
if ($line !~ /^#/) {
$lastBeforeComment = $.
}
push @content, $line;
}
close $f;
open $f, ">", "theFile.tmp" or die "can't open for writting\n$!";
if (!$done) {
print $f @content[0..$lastBeforeComment-1],"SomeParameter A\n",@content[$lastBeforeComment..$#content];
} else {
print $f @content;
}
close $f;
Run Code Online (Sandbox Code Playgroud)
确定后添加以下内容:
rename "theFile.tmp", "theFile"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10427 次 |
| 最近记录: |