skip to Main Content

I have 1344 ascii files with 3 columns and 68 rows of numerical values (no text/strings). They do not have any header, and the columns are space delimited.
I want to extract the value at 2nd column and 7th row from each one of those files, to create one file with one column and 1344 rows.

Example file 1:
0.11 3.1450 0.03
0.12 3.1210 0.04
0.13 3.1500 0.02
0.14 3.1530 0.03
0.15 3.1720 0.02
0.16 3.1170 0.04
0.17 3.1220 0.02
...

Example file 2:
0.11 3.1150 0.03
0.12 3.1410 0.04
0.13 3.2300 0.02
0.14 3.1230 0.03
0.15 3.3720 0.02
0.16 3.1370 0.02
0.17 3.2510 0.04
...

Output file:
3.1220
3.2510
...

I tried the following code:

awk '{for (i=7) {getline}; print NR,$2}' *

It gives me an error that the term is not recognised.

2

Answers


  1. Chosen as BEST ANSWER

    I just found another solution in matlab and posting the script here, in case anyone else needs it in future:

    dts = tabularTextDatastore('file location');
    files = dts.Files;
    data = zeros(1344,1);
    for i = 1:1:length(files)
        file_i = load(files{i});
        data(i) = file_i(7,2);
    end
    

  2. Using a small set of data for demonstration purposes:

    $ head f1 f2 f3
    ==> f1 <==
    1 2 3
    4 5 6
    7 8 9
    
    ==> f2 <==
    a b c
    d e f
    g h i
    
    ==> f3 <==
    A B C
    D E F
    G H I
    

    One awk idea to extract the 2nd column from the 2nd row in each file:

    $ awk 'FNR==2 { print $2; nextfile }' f1 f2 f3
    5
    e
    E
    

    Where:

    • FNR==2 – if this is the 2nd record of a file
    • print $2 – print 2nd column
    • nextfile – cease processing current file and begin processing next file

    For OP’s requirement we replace 2 with 7:

    awk 'FNR==7 { print $2; nextfile }' *
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search