我有以下格式的資料
ABC-ERW 12344 ZYX 12345
FFANKN 2345 QW [123457, 89053]
FAFDJ-ER 1234 MNO [6532, 789, 234578]
我想使用 sed 或 awk 創建以下格式的資料。
ABC-ERW 12344 ZYX 12345
FFANKN 2345 QW 123457
FFANKN 2345 QW 89053
FAFDJ-ER 1234 MNO 6532
FAFDJ-ER 1234 MNO 789
FAFDJ-ER 1234 MNO 234578
我可以提取括號之前的資料,但我不知道如何將相同的資料與括號中的資料重復連接。
我的努力 : -
# !/bin/bash
while IFS= read -r line
do
echo "$line"
cnt=`echo $line | grep -o "\[" | wc -l`
if [ $cnt -gt 0 ]
then
startstr=`echo $line | awk -F[ '{print $1}'`
echo $startstr
intrstr=`echo $line | cut -d "[" -f2 | cut -d "]" -f1`
echo $intrstr
else
echo "$line" >> newfile.txt
fi
done < 1.txt
我能夠獲得第一部分,并且在新檔案中保持沒有“[”的行,但我不知道如何獲取“[”中的值并在最后傳遞它,因為“[”中的變數數量不斷隨機變化.
問候
uj5u.com熱心網友回復:
使用您顯示的示例,請嘗試以下awk代碼。
awk '
match($0,/\[[^]]*\]$/){
num=split(substr($0,RSTART 1,RLENGTH-2),arr,", ")
for(i=1;i<=num;i ){
print substr($0,1,RSTART-1) arr[i]
}
next
}
1
' Input_file
說明:為上述代碼添加詳細說明。
awk ' ##Starting awk program from here.
match($0,/\[[^]]*\]$/){ ##Using match function to match from [ till ] at the end of line.
num=split(substr($0,RSTART 1,RLENGTH-2),arr,", ") ##Splitting matched values by regex above and passing into array named arr with delimiters comma and space.
for(i=1;i<=num;i ){ ##Running for loop till value of num.
print substr($0,1,RSTART-1) arr[i] ##printing sub string before matched along with element of arr with index of i.
}
next ##next will skip all further statements from here.
}
1 ##1 will print current line.
' Input_file ##Mentioning Input_file name here.
uj5u.com熱心網友回復:
建議簡單的awk腳本:
awk 'NR==1{print}{for (i=2;i<NF;i )print $1, $i}' FS="( \\\[)|(, )|(\\\]$)" input.1.txt
解釋:
FS="( \\\[)|(, )|(\\\]$)"將awk欄位分隔符設定為 [ , ]EOL
這將使有趣的欄位$2--->$FN被附加到$1
NR==1{print} 僅按原樣列印第一行。
{for (i=2;i<NF;i )print $1, $i}對于第二行,列印:當前欄位附加的欄位 $1。
uj5u.com熱心網友回復:
這可能對您有用(GNU sed):
sed -E '/(.*)\[([^,]*), /{s//\1\2\n\1[/;P;D};s/[][]//g' file
將字串匹配到左方括號以及逗號和空格之前的字串。
用前導和尾隨匹配字串替換整個匹配項,然后是換行符和前導匹配字串。
列印/洗掉第一行并重復。
上述任何重復的最后一行都將失敗,因為沒有尾隨逗號空格,在這種情況下,還應洗掉左方括號和右方括號。
選擇:
sed -E ':a;s/([^\n]*)\[([^,]*), /\1\2\n\1[/;ta;s/[][]//g' file
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/445477.html
上一篇:根據欄位數連接列
下一篇:組合.wav檔案的排列
