在Linux脚本中有条件地添加或附加到文件

5

我希望通过脚本修改一个文件。需要做到以下几点:
如果特定的字符串不存在,则添加它。

因此,我创建了以下脚本:

#!/bin/bash  
if grep -q "SomeParameter A" "./theFile"; then  
echo exist  
else  
   echo doesNOTexist  
   echo "# Adding parameter" >> ./theFile    
   echo "SomeParameter A" >> ./theFile    
fi

这个代码可以工作,但是我需要做一些改进。
我认为最好的方法是先检查 "SomeParameter" 是否存在,然后再看它是否跟着 "A" 或者 "B"。如果是 "B",就把它变成 "A"。
否则,在最后一个注释块的开头之前添加字符串(像我现在做的那样)。
我不擅长脚本编写。
谢谢!


a) 你认为最后一块注释是什么? b) 当你说“Some Parameter”后面跟着“A”或“B”,是指它们之间只有一个空格还是多个空格? - bbaja42
@aabbaja42: a)文件末尾有一系列以#开头的行,用于注释。如果可以的话,我想在这些行之前写入内容。 b)我正在努力使其更加健壮,并考虑到可能存在多个空格的情况。 - Jim
3个回答

8
首先,如果已有任何 SomeParameter 行,请更改它们。这将适用于类似 SomeParameterSomeParameter B 的行,且可以包含任意数量的额外空格:
sed -i -e 's/^ *SomeParameter\( \+B\)\? *$/SomeParameter A/' "./theFile"

如果该行不存在,则添加以下行:
if ! grep -qe "^SomeParameter A$" "./theFile"; then
    echo "# Adding parameter" >> ./theFile    
    echo "SomeParameter A" >> ./theFile    
fi

2
awk 'BEGIN{FLAG=0}
     /parameter a/{FLAG=1}
     END{if(flag==0){for(i=1;i<=NR;i++){print}print "adding parameter#\nparameter A#"}}' your_file

BEGIN{FLAG=0}-在文件处理开始之前初始化一个标志变量。

/parameter a/{FLAG=1}-如果在文件中找到参数,则设置标志。

END{if(flag==0){for(i=1;i<=NR;i++){print}print "添加参数#\n参数A#"}}-最后在文件末尾添加这些行。


如果你能解释一下你在做什么,那就太好了! - Jim
@Jim...仅仅因为它没有解释,你就应该将其投票否定。 - Vijay

-1
一个Perl的一行命令
perl -i.BAK -pe 'if(/^SomeParameter/){s/B$/A/;$done=1}END{if(!$done){print"SomeParameter A\n"}} theFile

将创建一个备份文件theFile.BAK(-i选项)。还有一个更详细的版本,考虑到最后的注释,需要进行测试。应该保存在文本文件中并执行perl my_script.plchmod 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;

一旦确认无误,然后添加以下内容:

rename "theFile.tmp", "theFile"

我需要从一个规范文件中完成它。我不确定是否可以使用perl。 - Jim
当然,你可以用Perl读取它,但是你如何读取规范文件呢? - Nahuel Fouilleul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接