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

在linux脚本中有条件地添加或附加到文件,linux,bash,unix,scripting,Linux,Bash,Unix,Scripting,我需要通过脚本修改文件。 我需要执行以下操作: 如果特定字符串不存在,则将其追加 因此,我创建了以下脚本: #!/bin/bash if grep -q "SomeParameter A" "./theFile"; then echo exist else echo doesNOTexist echo "# Adding parameter" >> ./theFile echo "SomeParameter A" >> ./t

我需要通过脚本修改文件。
我需要执行以下操作:
如果特定字符串不存在,则将其追加

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

#!/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”。
否则,在最后一块注释开始之前追加字符串(与我一样)。
我该怎么做?
我不擅长编写脚本。
谢谢

perl一行程序

perl -i.BAK -pe 'if(/^SomeParameter/){s/B$/A/;$done=1}END{if(!$done){print"SomeParameter A\n"}} theFile
将创建file.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;
awk'开始{FLAG=0}
/参数a/{FLAG=1}

结束{if(flag==0){for(i=1;i首先,更改任何
SomeParameter
行(如果它们已经存在)。这应该适用于像
SomeParameter
SomeParameter 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

A)你认为最后一批评论是什么?B)你的意思是“某个参数”后面是“A”还是“B”?,这是否意味着它们之间只有一个或多个空格?@bbaja42:a)在文件注释内容的末尾有一系列以
#
开头的行。如果容易/可能的话,我想在这些行之前进行编写。b)我正在努力使其健壮,并考虑到存在多个空间的可能性,因此我需要从规范fi中执行此操作le.我不确定我是否可以使用perlsure,你可以用perl阅读它,你如何阅读规范文件?如果你能解释你在做什么,那就太好了!@Jim…只是它没有解释并不意味着你应该否决投票。
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