2012-10-22 33 views
5

我需要通過腳本修改文件。
我需要執行以下操作:
如果特定的字符串不存在,請將其附加。有條件地添加或附加到Linux腳本中的文件

因此,我創建了下面的腳本:

#!/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」。
否則追加字符串(就像我這樣做),但在最後一塊評論的開始之前。
我該怎麼做?
我不擅長腳本編寫。
謝謝!

+0

一)你怎麼考慮的最後一個塊註釋? b)你的意思是「某些參數」後面跟着「A」或「B」,這是否意味着它們之間只有一個或多個空格? – bbaja42

+0

@ bbaja42:a)在文件註釋結束時有一系列以'#'開頭的行。如果它很容易/可能,我想在這些之前寫。 b)我正在努力使其穩定並考慮到存在超過1個空間的機會 – Jim

回答

-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" 
+0

我需要從spec文件中做到這一點。我不確定我是否可以使用perl – Jim

+0

當然,您可以閱讀perl,你如何閱讀spec文件? –

+0

我不讀它。我會把腳本放在一個spec文件中 – Jim

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}的開始之前-initializing一個標誌變量文件處理。

/parameter a/{FLAG=1} - 如果在文件中找到參數,則設置標誌。

END{if(flag==0){for(i=1;i<=NR;i++){print}print "adding parameter#\nparameter A#"}}在文件

+0

如果你能解釋你在做什麼,那會很棒! – Jim

+0

@Jim ...只是它沒有expalnation並不代表你應該投票。 – Vijay

+0

我做了**沒有** downvote !!!!我會upvote(+1)糾正這一點。 – Jim

7

首先結束 - 最後添加的行,如果他們已經存在更改任何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