我有一個 csv 檔案讓我們說行
cat lines
1:abc
6:def
17:ghi
21:tyu
我想實作這樣的目標
1:6:abc
6:17:def
17:21:ghi
21::tyu
嘗試以下代碼無效
awk 'BEGIN{FS=OFS=":"}NR>1{nln=$1;cl=$2}NR>0{print $1,nln,$2}' lines
1::abc
6:6:def
17:17:ghi
21:21:tyu
你能幫忙嗎?
uj5u.com熱心網友回復:
這是一個潛在的 AWK 解決方案:
cat lines
1:abc
6:def
17:ghi
21:tyu
awk -F":" '{num[NR]=$1; letters[NR]=$2}; END{for(i=1;i<=NR;i ) print num[i] ":" num[i 1] ":" letters[i]}' lines
1:6:abc
6:17:def
17:21:ghi
21::tyu
格式化:
awk '
BEGIN {FS=OFS=":"}
{
num[NR] = $1;
letters[NR] = $2
}
END {for (i = 1; i <= NR; i )
print num[i], num[i 1], letters[i]
}
' lines
1:6:abc
6:17:def
17:21:ghi
21::tyu
uj5u.com熱心網友回復:
基本上這是你的解決方案,但我切換了代碼塊的順序并添加了END塊以輸出最后一條記錄,你很接近:
awk 'BEGIN{FS=OFS=":"}FNR>1{print p,$1,q}{p=$1;q=$2}END{print p,"",q}' file
解釋:
$ awk 'BEGIN {
FS=OFS=":" # delims
}
FNR>1 { # all but the first record
print p,$1,q # output $1 and $2 from the previous round
}
{
p=$1 # store for the next round
q=$2
}
END { # gotta output the last record in the END
print p,"",q # "" feels like cheating
}' file
輸出:
1:6:abc
6:17:def
17:21:ghi
21::tyu
uj5u.com熱心網友回復:
第一個解決方案:這是一個tac awk解決tac方案。僅使用所示樣本進行撰寫和測驗。
tac Input_file |
awk '
BEGIN{
FS=OFS=":"
}
{
prev=(prev?$2=prev OFS $2:$2=OFS $2)
}
{
prev=$1
}
1
' | tac
說明:為上述代碼添加詳細說明。
tac Input_file | ##Printing lines from bottom to top of Input_file.
awk ' ##Getting input from previous command as input to awk.
BEGIN{ ##Starting BEGIN section from here.
FS=OFS=":" ##Setting FS and OFS as colon here.
}
{
prev=(prev?$2=prev OFS $2:$2=OFS $2) ##Creating prev if previous NOT NULL then add its value prior to $2 with prev OFS else add OFS $2 in it.
}
{
prev=$1 ##Setting prev to $1 value here.
}
1 ##printing current line here.
' | tac ##Sending awk output to tac to make it in actual sequence.
第二種解決方案:僅添加awk2 次將 Input_file 傳遞給它的解決方案。
awk '
BEGIN{
FS=OFS=":"
}
FNR==NR{
if(FNR>1){
arr[FNR-1]=$1
}
next
}
{
$2=(FNR in arr)?(arr[FNR] OFS $2):OFS $2
}
1
' Input_file Input_file
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/446361.html
上一篇:視窗默認檔案夾以不同的語言顯示
下一篇:在新行上合并2個文本檔案
