2017-04-13 43 views
0

我有兩個文件:令牌使用從文件中的值,並創建替換多個文件,一個一個替換每個

文件1:

key1 
key2 
key3 

文件2:

some useful or useless text 
::tok:: 
some more useful or useless text 

我想創建多個文件:

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 

我偏激小白當它涉及到awk或者sed。我可以使用perl腳本或bash腳本來完成上述操作。有沒有辦法使用sed或awk來做到這一點?

編輯:所要求的Perl腳本我使用上面做任務

$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中:

$ 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 
相關問題