簡體   English   中英

使用Bash對所有列進行排序?

[英]Using Bash to sort all columns?

我有一個輸入文件(限制為2條記錄,列數不受限制),例如:

6 5 9 4.5 
3 9 13 1

我想使用bash排序腳本,該腳本將對文件中的每一列進行排序並產生輸出:

3 5 9 1
6 9 13 4.5

這樣做的目的是我只想比較並提取每列中的最大列。

我想對所有列進行排序,然后僅打印出文件的最后一條記錄將是一個很好的解決方案,但是我很難找到可以對每一列進行排序的代碼。 只要bash沒有達到EOF,是否有可能通過“ for循環”進行迭代,並對當前字段的每一列進行排序?

重要說明**可以有任意數量的列,但是只有2條記錄。 **

假設所有數字都在一個名為text的文件中,看起來像這樣

6 5 9 4.5
3 9 13 1

如果每個數字都由一個空格分隔,則可以執行此操作。

#array of all the numbers in the first line of text
num=($(head -n 1 text))

#array for each resulting line
row1=()
row2=()

#iterate num length times
for (( i=1; i<=${#num[@]}; ++i )); do

    #cut the ith column from the file and sort it
    col=($(cat text | cut -d ' ' -f$i | sort -n))

    #split column into its respective rows
    row1+=( ${col[0]} )
    row2+=( ${col[1]} )
done

#write results out to file
echo ${row1[@]} >> sorted_text
echo ${row2[@]} >> sorted_text

這將導致一個名為sorted_text的文件,如下所示

3 5 9 1
6 9 13 4.5

如果您只希望具有最大數字的行,則從輸出中刪除row1

這樣做的目的是我只想比較並提取每列中的最大列。

在這種情況下,假設輸入文件稱為data

# Read the two lines into arrays:
{ read line1 ; read line2 ; } <data     
line1=($line1)
line2=($line2)
# Compare the two lines, finding the max for each column
out=
for ((i=0; i<${#line1[@]}; i++))
do
    max=${line1[$i]}
    [[ 1 = "$(echo "${line2[$i]} > ${line1[$i]}" | bc)" ]] && max=${line2[$i]}
    out="$out $max"
done
# Show results
echo $out

上面產生輸出:

6 9 13 4.5

我們可以使用此命令

awk'{for(i = 1; i <= NF; i ++); 打印}'| 排序filename.txt

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM