Domanda

I need to reverse the fields of a text file containing:

Computer science is fun
I also enjoy math
But I don't like science

I need the awk to output:

line 1: Computer science is fun
line 1 reversed: fun is science Computer
line 2: I also enjoy math
line 2 reversed: math enjoy also I

....... and so on. This is what I have right now:

BEGIN {print "start"}
{
    for(i=NF; i>=1; i--)
    {
        printf "line %d: %s\n", NR , $0;
        printf "line %d: reversed: %s", NR, $i;
    }
}
È stato utile?

Soluzione

You were close:

BEGIN {print "start"}
{
    printf "line %d: %s\n", NR , $0
    printf "line %d: reversed:", NR
    for(i=NF; i>=1; i--)
    {
        printf " %s", $i
    }
    print ""
}

The above is assuming you don't care about white space between fields.

Altri suggerimenti

Try:

awk '{for (i=NF; i>0; i--) printf("%s ",$i);print ""}' input.txt
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top