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」にします。
それ以外の場合は、コメントの最後のブロックの開始前に文字列を追加します (私が行うように)。
どうすればこれを行うことができますか?
私はスクリプトが苦手です。
ありがとう!

4

3 に答える 3

7

まず、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
于 2012-10-23T09:37:58.443 に答える
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 "adding parameter#\nparameter A#"}}-最後にファイルの最後に行を追加します

于 2012-10-22T09:19:23.383 に答える
-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.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;

問題がなければ、次を追加します。

rename "theFile.tmp", "theFile"
于 2012-10-22T08:59:09.660 に答える