A.txt 包含:
/*333*/
asdfasdfadfg
sadfasdfasgadas
@@@
/*555*/
hfawehfihohawe
aweihfiwahif
aiwehfwwh
@@@
/*777*/
jawejfiawjia
ajwiejfjeiie
eiuehhawefjj
@@@
B.txt 包含:
555
777
我想為 B.txt 中找到的每個字串創建回圈,然后輸出 '/*'[the string] 直到第一個 '@@@' 遇到每個自己的檔案之前(字串名稱也用作檔案名)。因此,根據上面的示例,結果應該是:
555.txt,其中包含:
/*555*/
hfawehfihohawe
aweihfiwahif
aiwehfwwh
和 777.txt,其中包含:
/*777*/
jawejfiawjia
ajwiejfjeiie
eiuehhawefjj
我試過這個腳本,但它什么也沒輸出:
for i in `cat B.txt`; do echo $i | awk '/{print "/*"$1}/{flag=1} /@@@/{flag=0} flag' A.txt > $i.txt; done
先感謝您
uj5u.com熱心網友回復:
使用您顯示的示例,請嘗試以下awk代碼。用 GNU 撰寫和測驗awk應該可以在任何awk.
awk '
FNR==NR{
if($0~/^\/\*/){
line=$0
gsub(/^\/\*|\*\/$/,"",line)
arr[ count]=$0
arr1[line]=count
next
}
arr[count]=(arr[count]?arr[count] ORS:"") $0
next
}
($0 in arr1){
outputFile=$0".txt"
print arr[arr1[$0]] >> (outputFile)
close(outputFile)
}
' file1 file2
說明:為上述代碼添加詳細說明。
awk ' ##Starting awk program from here.
FNR==NR{ ##Checking condition FNR==NR which will be TRUE when file1 is being read.
if($0~/^\/\*/){ ##Checking condition if current line starts with /* then do following.
line=$0 ##Setting $0 to line variable here.
gsub(/^\/\*|\*\/$/,"",line) ##using gsub to globally substitute starting /* and ending */ with NULL in line here.
arr[ count]=$0 ##Creating arr with index of count and value is $0.
arr1[line]=count ##Creating arr1 with index of line and value of count.
next ##next will skip all further statements from here.
}
arr[count]=(arr[count]?arr[count] ORS:"") $0 ##Creating arr with index of count and keep appending values of same count values with current line value.
next ##next will skip all further statements from here.
}
($0 in arr1){ ##checking if current line is present in arr1 then do following.
outputFile=$0".txt" ##Creating outputFile with current line .txt value here.
print arr[arr1[$0]] >> (outputFile) ##Printing arr value with index of arr1[$0] to outputFile.
close(outputFile) ##Closing outputFile in backend to avoid too many opened files error.
}
' file1 file2 ##Mentioning Input_file names here.
uj5u.com熱心網友回復:
通過提供的示例資料對代碼進行一些更改即可獲得所需的結果:
while read -r f
do
awk -v var="/[*]$f[*]/" '$0 ~ var {flag=1} /@@@/{flag=0} flag' A.txt > "$f".txt
done < B.txt
cat 555.txt
/*555*/
hfawehfihohawe
aweihfiwahif
aiwehfwwh
cat 777.txt
jawejfiawjia
ajwiejfjeiie
eiuehhawefjj
這能解決你的問題嗎?
uj5u.com熱心網友回復:
這是另一個awk解決方案:
awk '
FNR == NR {
map["/*" $0 "*/"] = $0
next
}
$0 in map {
fn = map[$0] ".txt"
}
/^@@@$/ {
close(fn)
fn = ""
}
fn {print > fn}' B.txt A.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/476679.html
上一篇:將platformio.ini環境提取到bash陣列的awk
下一篇:回圈從bash中的值創建aaDF
