AC solution using awk and statement just like C.


  • 39
    I

    Just feel free to use for and if.
    You can append string easily, for example, s = s a to append a with s.

    awk '
    {
        for (i = 1; i <= NF; i++) {
            if(NR == 1) {
                s[i] = $i;
            } else {
                s[i] = s[i] " " $i;
            }
        }
    }
    END {
        for (i = 1; s[i] != ""; i++) {
            print s[i];
        }
    }' file.txt

  • 0
    L
    column=`head -n1 file.txt|awk '{print NF}'`
    for((i=1;i<=$column;i++))
    do
    
    while read line;do
    temp=`echo $line|awk '{print $v1}' v1="$i"`
    str1=${str1}" $temp"
    done < file.txt
    
    echo $str1
    str1=""
    done

  • 0
    L

  • 0
    M

    I am new to awk, so anybody cares to explain what does the "for (i = 1; s[i] != ""; i++)" mean? Especially the s[i]!=""?


  • 0
    I

    END part will run after it dealt with every line.
    After dealing with all the lines, the s[] array is what we want.
    END part is to print the s[], this for loop will end when s[i] is empty.
    Because the lines may have different number of words, I cannot find the length of s[] easily. If you have a better way, please tell me :).


  • 0
    H

    I tried your answer on my ubuntu, it just kept outputting blank and never stopped...but it was accepted by QJ. I really don't know what happened to my ubuntu...


  • 0
    I

    Test ok in Ubuntu 15.02. Try following:

    1. Save the code as solution.sh
    2. chmod +x solution.sh
    3. ./solution.sh

  • 0
    H

    thank you for your code and i saw where i made the mistake. it's an extra space. your code is brilliant.


  • 0
    I

    It is really a brilliant solution...!!! mind-blowing!


  • 0
    H

    @lancer2002 this solution suffers Memory Limit Exceeded


  • 0
    R

    I'm new to awk as well, could someone please explain the initial for loop to me? Thanks!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.