Awk - how to print variable with string

前端 未结 2 992
别跟我提以往
别跟我提以往 2021-01-24 10:30

I have this input and I would like to learn how to save string after = to variable and use it for output filename and in the first line of output that will start with \"#\"

2条回答
  •  渐次进展
    2021-01-24 10:57

    Untested code follows:

    /^c/ { X[$2] = $3 }
    /^c end/ { outfile = X["column2="] X["ROIysiz="] X["column3="]
               print "#", X["column2="], X["RedNumDa="] > outfile }
    !/^c/ { print $0 >> outfile }
    

    EDIT: The code is now tested:

    $ cat x
    c ROIysiz= 28
    c column1= HJD
    c RedNumDa= 18262
    c column3= ERROR
    c column2= FLUX
    c end header ---------------------------------------------------------------------------------------
    2.458375368952875026e+06 -8.420548421860798386e-04 7.020812100561693928e-03
    2.458375579737625085e+06 -5.579159672996818198e-03 1.285380720081348528e-03
    2.458376278315599542e+06 -7.634101850411220518e-03 2.481065693991901019e-03
    2.458376347386624664e+06 7.223482191697593166e-04 2.319993894372075760e-03
    2.458376416108166799e+06 5.238757879614985152e-03 1.389030320490110878e-03
    2.458376485913363751e+06 6.777606553373448882e-03 8.887787066666734273e-04
    2.458377048675692175e+06 1.950435173388009522e-02 3.242344477396308117e-03
    2.458377185153110884e+06 1.885754079806525874e-02 2.090836971653367571e-03
    $ awk '
    /^c/ { X[$2] = $3 }
    /^c end/ { outfile = X["column2="] X["ROIysiz="] X["column3="]
               print "#", X["column2="], X["RedNumDa="] > outfile }
    !/^c/ { print $0 >> outfile }
    ' x
    $ cat FLUX28ERROR
    # FLUX 18262
    2.458375368952875026e+06 -8.420548421860798386e-04 7.020812100561693928e-03
    2.458375579737625085e+06 -5.579159672996818198e-03 1.285380720081348528e-03
    2.458376278315599542e+06 -7.634101850411220518e-03 2.481065693991901019e-03
    2.458376347386624664e+06 7.223482191697593166e-04 2.319993894372075760e-03
    2.458376416108166799e+06 5.238757879614985152e-03 1.389030320490110878e-03
    2.458376485913363751e+06 6.777606553373448882e-03 8.887787066666734273e-04
    2.458377048675692175e+06 1.950435173388009522e-02 3.242344477396308117e-03
    2.458377185153110884e+06 1.885754079806525874e-02 2.090836971653367571e-03
    

    The first line, in the /^c/ pattern, saves each header line (the lines that begin with the letter c). The second and third lines, in the /^c end/ pattern, compute the output filename using string concatenation to join the various header values, then writes the first line of the output file in a similar manner, using the , operator to separate fields. The fourth line, in the !/^c/ pattern, prints each non-header line, unchanged, to the output file. Associative array X stores each header key as its index and the associated value at its value.

提交回复
热议问题