
我有一個亂序的文件。
文件1
1 HD;BSkyB:11097:VC23M5O25P0S1:S28.2E:23000:2305=27:2307=NAR@4;2306=eng@106:2308;2309=eng:0:21000:2:2066:0
2 HD;BSkyB:11097:VC23M5O25P0S1:S28.2E:23000:2315=27:2316=NAR@4;2317=eng@106:2318;2319=eng:0:21020:2:2066:0
3 HD;BSkyB:11097:VC23M5O25P0S1:S28.2E:23000:2320=27:2321=NAR@4;2322=eng@106:2323;2324=eng:0:21030:2:2066:0
ITV HD;BSkyB:11097:VC23M5O25P0S1:S28.2E:23000:2305=27:2307=NAR@4;2306=eng@106:2308;2309=eng:0:21000:2:2066:0
還有第二個文件
3 HD
1 HD
2 HD
我想掃描文件二,並對文件1重新排序,並將剩餘的文件修改到文件末尾,所以最終結果是
3 HD;BSkyB:11097:VC23M5O25P0S1:S28.2E:23000:2320=27:2321=NAR@4;2322=eng@106:2323;2324=eng:0:21030:2:2066:0
1 HD;BSkyB:11097:VC23M5O25P0S1:S28.2E:23000:2305=27:2307=NAR@4;2306=eng@106:2308;2309=eng:0:21000:2:2066:0
2 HD;BSkyB:11097:VC23M5O25P0S1:S28.2E:23000:2315=27:2316=NAR@4;2317=eng@106:2318;2319=eng:0:21020:2:2066:0
ITV HD;BSkyB:11097:VC23M5O25P0S1:S28.2E:23000:2305=27:2307=NAR@4;2306=eng@106:2308;2309=eng:0:21000:2:2066:0
有任何想法嗎?
提前致謝。
答案1
根據檔案的大小,將每一行載入到陣列中將是處理此問題的最簡單方法。使用索引檔案取得物件鍵(對陣列中項目的參考)並寫入該行、循環等。
我看到你標記了 Linux/bash,所以這裡有一些幫助資訊。
Bash 陣列僅具有編號索引,但它們是稀疏的,即您不必定義所有索引。可以透過將數組項括在括號中來分配整個數組:
arr=(Hello World)
可以使用熟悉的陣列語法來指派單一項目(除非您習慣使用 Basic 或 Fortran):
arr[0]=Hello
arr[1]=World
但是當你想引用一個數組項時,它會變得有點難看:
echo ${arr[0]} ${arr[1]}
引用手冊頁:需要使用大括號以避免與路徑名擴充發生衝突。
此外,還可以使用以下時髦的結構:
${arr[*]} # All of the items in the array
${!arr[*]} # All of the indexes in the array
${#arr[*]} # Number of items in the array
${#arr[0]} # Length of item zero
${!arr[*]} 是 bash 中相對較新的補充,它不是原始數組實現的一部分。
以下範例顯示了一些簡單的陣列用法(請注意「[index]=value」賦值以指派特定索引):
#!/bin/bash
array=(one two three four [5]=five)
echo "Array size: ${#array[*]}"
echo "Array items:"
for item in ${array[*]}
do
printf " %s\n" $item
done
echo "Array indexes:"
for index in ${!array[*]}
do
printf " %d\n" $index
done
echo "Array items and indexes:"
for index in ${!array[*]}
do
printf "%4d: %s\n" $index ${array[$index]}
done
運行它會產生以下輸出: 陣列大小:5 陣列項:
one
two
three
four
five
數組索引:
0
1
2
3
5
數組項和索引:
0: one
1: two
2: three
3: four
5: five
請注意,可以使用“@”符號代替“" 在 ${arr[ 等結構中]},結果是相同的,除非擴展到帶引號的字串中的陣列項。在這種情況下,行為與展開「$" 和 "$@" 在引號的字串中: "${arr[]}" 將所有項目作為單字返回,而 "${arr[@]}" 將每個項目作為單獨的單字返回。
有關 bash 數組的更多資訊可以在以下位置找到:http://www.linuxjournal.com/content/bash-arrays
若要將檔案載入到陣列中,您可以使用類似的方法,使用 X 變數向陣列新增索引,或者您可以在迴圈內拉取自訂索引。
#!/bin/sh
files="`cat $1`"
for x in $lines
echo "$x"
done
答案2
awk -F';' '
NR == FNR {a[$1] = $0; next}
{print a[$0]; delete a[$0]}
END {for (l in a) print a[l]}' file1 file2