Printing everything except the first field with awk

前端 未结 16 2609
北恋
北恋 2020-12-04 07:04

I have a file that looks like this:

AE  United Arab Emirates
AG  Antigua & Barbuda
AN  Netherlands Antilles
AS  American Samoa
BA  Bosnia and Herzegovina         


        
相关标签:
16条回答
  • 2020-12-04 08:00

    The field separator in gawk (at least) can be a string as well as a character (it can also be a regex). If your data is consistent, then this will work:

    awk -F "  " '{print $2,$1}' inputfile
    

    That's two spaces between the double quotes.

    0 讨论(0)
  • 2020-12-04 08:00

    Let's move all the records to the next one and set the last one as the first:

    $ awk '{a=$1; for (i=2; i<=NF; i++) $(i-1)=$i; $NF=a}1' file
    United Arab Emirates AE
    Antigua & Barbuda AG
    Netherlands Antilles AN
    American Samoa AS
    Bosnia and Herzegovina BA
    Burkina Faso BF
    Brunei Darussalam BN
    

    Explanation

    • a=$1 save the first value into a temporary variable.
    • for (i=2; i<=NF; i++) $(i-1)=$i save the Nth field value into the (N-1)th field.
    • $NF=a save the first value ($1) into the last field.
    • {}1 true condition to make awk perform the default action: {print $0}.

    This way, if you happen to have another field separator, the result is also good:

    $ cat c
    AE-United-Arab-Emirates
    AG-Antigua-&-Barbuda
    AN-Netherlands-Antilles
    AS-American-Samoa
    BA-Bosnia-and-Herzegovina
    BF-Burkina-Faso
    BN-Brunei-Darussalam
    
    $ awk 'BEGIN{OFS=FS="-"}{a=$1; for (i=2; i<=NF; i++) $(i-1)=$i; $NF=a}1' c
    United-Arab-Emirates-AE
    Antigua-&-Barbuda-AG
    Netherlands-Antilles-AN
    American-Samoa-AS
    Bosnia-and-Herzegovina-BA
    Burkina-Faso-BF
    Brunei-Darussalam-BN
    
    0 讨论(0)
  • 2020-12-04 08:00

    A first stab at it seems to work for your particular case.

    awk '{ f = $1; i = $NF; while (i <= 0); gsub(/^[A-Z][A-Z][ ][ ]/,""); print $i, f; }'
    
    0 讨论(0)
  • 2020-12-04 08:05
    awk '{sub($1 FS,"")}7' YourFile
    

    Remove the first field and separator, and print the result (7 is a non zero value so printing $0).

    0 讨论(0)
提交回复
热议问题