我想用包含以下內容的檔案(這是MWE)中的每第n行(例如在這種情況下每2行)中的第n個連續常規行范圍替換檔案上的每次nth出現。foo1.txt0.txt
源檔案為0.txt:
The sun has its own light
foo
The moon reflects the sunlight
foo
The planet Earth receives both sunlight and moonlight
foo
目標檔案是1.txt:
source-text1
[(('f1','b1'), ('g1','h1'))]
source-text-2
[(('f2','b2'), ('g2','h2'))]
source-text-3
[(('f3','b3'), ('g3','h3'))]
應用替換,例如 'command_method' 0.txt 1.txt > 2.txt ,偽代碼,我會得到所需的輸出檔案如下,作為第三個2.txt檔案的列印輸出:
預期輸出為 2.txt:
The sun has its own light
source-text1
[(('f1','b1'), ('g1','h1'))]
The moon reflects the sunlight
source-text-2
[(('f2','b2'), ('g2','h2'))]
The planet Earth receives both sunlight and moonlight
source-text-3
[(('f3','b3'), ('g3','h3'))]
我試過了:
awk 'NR==FNR {a[NR]=$0; next} /foo/{gsub("foo", a[int(k /2)%3 2])} 1' 1.txt 0.txt > 2.txt
但這給了我2.txt:
The sun has its own light
[(('f1','b1'), ('g1','h1'))]
The moon reflects the sunlight
[(('f1','b1'), ('g1','h1'))]
The planet Earth receives both sunlight and moonlight
source-text-2
I don't have ideas anymore. I'm looking for a solution that can work with any size range of lines
uj5u.com熱心網友回復:
假設:
foo僅單獨出現在一行中- 如果
foo出現的次數多于我們有替換字串,請不要替換foo
設定:
$ cat 0.txt
The sun has its own light
foo
The moon reflects the sunlight
foo
The planet Earth receives both sunlight and moonlight
foo
The following line should NOT be replaced
foo
$ cat 1.txt
source-text1
[(('f1','b1'), ('g1','h1'))]
source-text-2
[(('f2','b2'), ('g2','h2'))]
source-text-3
[(('f3','b3'), ('g3','h3'))]
一個awk想法:
awk -v setsize=2 -v ptn="foo" ' # setsize == number of lines from first file that define a replacement set
# ptn == string to be replaced
FNR==NR { replace[ rcount]= $0 # start replacement string
for (i=1;i<setsize;i ) { # append to replacement string until we have read "setsize" lines into the replacement string
getline
replace[rcount]=replace[rcount] RS $0
}
next
}
$0~ptn { if ( pcount in replace) # if we have a replacement string then ...
$0=replace[pcount] # replace the current line
}
1 # print the current line
' 1.txt 0.txt
這會產生:
The sun has its own light
source-text1
[(('f1','b1'), ('g1','h1'))]
The moon reflects the sunlight
source-text-2
[(('f2','b2'), ('g2','h2'))]
The planet Earth receives both sunlight and moonlight
source-text-3
[(('f3','b3'), ('g3','h3'))]
The following line should NOT be replaced
foo
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442598.html
標籤:string bash replace text-processing
上一篇:如何在Dart/Flutter中一次多次將相同的值添加到串列中
下一篇:為什么json.loads('{"Testing":"Thisquo\\\\"teString"}'))不起作用?
