Alex
Alex

Reputation: 355

Create a new line for my last column using awk

I have the file:

A cars1 black NY
A cars2       W
A cars3 black SP

I would like to transform the last column into a new line and add the > symbol:

A cars1 black
>NY
A cars2       
>W
A cars3 black 
>SP

I tried the command below, but it did not work very well, maybe because of the missing values of the third column:

awk '{print $1,$2,$3,"\n"$4}'

Upvotes: 0

Views: 501

Answers (3)

dawg
dawg

Reputation: 103844

In awk you can do it 'mechanically':

$ awk '{for(i=1;i<NF;i++) printf "%s%s",$i,i==NF-1 ? ORS : OFS; print ">" $NF}' file
A cars1 black
>NY
A cars2
>W
A cars3 black
>SP

Upvotes: 1

James Brown
James Brown

Reputation: 37404

In awk:

$ awk '{$NF=ORS ">" $NF; print}' file

The point is to modify the last field $NF and then just print the whole record $0.

Upvotes: 1

Benjamin W.
Benjamin W.

Reputation: 52142

In sed:

$ sed 's/[[:blank:]]*\([^[:blank:]]*\)$/\n>\1/' infile
A cars1 black
>NY
A cars2
>W
A cars3 black
>SP

This takes the last sequence of blanks followed by non-blanks and substitutes them by a newline, > and the captured non-blanks.

Notice that some seds complain about inserting a newline like this. Alternatives are:

  • Insert a literal newline

    sed 's/[[:blank:]]*\([^[:blank:]]*\)$/\
    >\1/' infile
    
  • Insert an ANSI-escaped newline

    sed 's/[[:blank:]]*\([^[:blank:]]*\)$/'$'\n''>\1/' infile
    
  • Command substitution

    sed 's/[[:blank:]]*\([^[:blank:]]*\)$/'"$(printf '\n')"'>\1/' infile
    

Upvotes: 3

Related Questions