2017-04-13 5 views
0

私は2つのファイルを持っています複数のファイル:トークン置換ファイルからの値を使用して作成し、複数のファイル、1つの置換のための1それぞれが

file_key1:

some useful or useless text 
key1 
some more useful or useless text 

file_key2:

some useful or useless text 
key2 
some more useful or useless text 

file_key3:

some useful or useless text 
key3 
some more useful or useless text 

それはsedのかawkのために来るとき、私は極度のnoobです。私は上記のperlスクリプトまたはbashスクリプトを使用して行うことができます。 sedまたはawkを使ってそれを行う方法はありますか?

編集:私は上記のタスクを行うために使用していますperlスクリプトを要求したとして、awkでは

$newFileCount= 1; 

open IFH,$filename || die "cannot open the file"; 

sub CreateNewFiles{ 

     my ($cid) = @_; 
     open TIFH, $templateFile; # this is the template file file2 from the above problem description 
     open OFH,">$templateFileTemp"; 
     while(<TIFH>) { 
       s/::tok::/$cid/g; 
       print OFH $_; 
     } 
     close TIFH; 
     close OFH; 
     move($templateFileTemp,$newFilePrefix.$newFileCount.".ext"); # using a library File::Copy for move operation 

} 
while(<IFH>) { 
     chomp($_); 
     $newFileCount= $newFileCount + 1; 
     CreateNewFiles($_); 

} 
+3

perlスクリプトやbashスクリプトで実行できるのであれば、なぜsedまたはawkでそれをしたいのですか?そしてもしあなたがしたら...それはおそらくあなたがこれまでに試したことを示す良い答えを出すのを助けるでしょう。 – Sobrique

+0

@Sobrique私はちょうどこれらのことをするsed/awkの方法を学びたかった。私はタスクの最小のためのPerlのスクリプトを書かなければならないインスタンスに直面している、私は確かにsed/awkを学ぶことに価値があると思います。とにかく、上の編集を見てください、私はperlスクリプトで質問を更新しました – Ravi

+0

私はちょうど実際に同意しません。 'perl'はプログラミング言語であり、すべてをうまくやり遂げることができます。 – Sobrique

答えて

2

$ awk ' 
NR==FNR {     # for the data file 
    b=b (NR==1?"":ORS) $0 # buffer the records from the data file 
    next     # next record 
} 
{ 
    close(file)   # close previous file 
    file="file_" $1  # name current file 
    t=b     # t is for tmp, b for buffer, baby 
    sub(/::tok::/,$1,t) # replace token with the key 
    print t > file   # dump the t to file 
}' file2 file1    # mind the order 
+0

は、awkのNR FNR ORSの特別なキーワードですか? – Ravi

+1

@Raviはい。 'NR'は' FNR'とは対照的に(グローバル)レコードの数であり、現在のファイルのレコード数であり、 'ORS'は出力レコードのセパレータです。通常、レコードは改行で終わりますが、必然的に終了します。 –

0

これを試してみてください -

$head f? 
==> f1 <== 
key1 
key2 
key3 

==> f2 <== 
some useful or useless text 
::tok:: 
some more useful or useless text 

$cat script.sh 
#!/bin/bash 
file1=$1 
file2=$2 
while IFS= read line 
do 
awk -v line="$line" '{gsub(/::tok::/,line); print > "fil_"line }' $file2 
done < $file1 

$./script.sh f1 f2 
$head fil_key? 
==> fil_key1 <== 
some useful or useless text 
key1 
some more useful or useless text 

==> fil_key2 <== 
some useful or useless text 
key2 
some more useful or useless text 

==> fil_key3 <== 
some useful or useless text 
key3 
some more useful or useless text 
関連する問題