【问题标题】:Using Bash to sort all columns?使用 Bash 对所有列进行排序?
【发布时间】:2014-03-22 18:49:09
【问题描述】:

我有一个输入文件(限制为 2 条记录,列数不限)如:

6 5 9 4.5 
3 9 13 1

我想使用 bash 排序脚本对文件中的每一列进行排序并生成输出:

3 5 9 1
6 9 13 4.5

这样做的目的是我想比较并只提取每列中最大的。

我认为对所有列进行排序,然后打印出文件的最后一条记录将是一个很好的解决方案,但是我无法找到对每一列进行排序的代码。只要不到达 EOF,bash 是否可以遍历“for 循环”,并对当前字段的每一列进行排序?

重要说明 ** 可以有任意数量的列,但只有 2 条记录。 **

【问题讨论】:

    标签: bash sorting io


    【解决方案1】:

    这样做的目的是我想比较并只提取每列中最大的。

    在这种情况下,假设输入文件名为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
    

    【讨论】:

    • 这会导致..“第 11 行:bc:找不到命令。”是否有一些语法错误阻止 bc 正确输入?
    • @Blued00d 为了检查是否存在拼写错误,我只是将这个答案中的代码复制回了我的电脑。它运行没有错误。 bc 是否已安装并在您的系统上运行?比如你在命令行运行echo 4+6 | bc,是不是返回10?
    【解决方案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

    【讨论】:

      【解决方案3】:

      我们可以使用这个命令

      awk '{for(i=1;i

      【讨论】:

        猜你喜欢
        • 2021-02-07
        • 2014-05-23
        • 1970-01-01
        • 2013-08-22
        • 2015-06-29
        • 2015-08-14
        • 2017-05-21
        • 2018-07-18
        • 1970-01-01
        相关资源
        最近更新 更多