UPDATED QUESTION
Ok, so I have a file with lines like this:
44:) 2.884E-02 0.000E+00 0.000E+00 2.780E+02 0.000E+00 0.000E+00 9.990E+02
45:) 2.884E-02 0.000E+00 0.000E+00 2.780E+02 0.000E+00 0.000E+00 9.990E+02
1:) 3.593E-02 0.000E+00 0.000E+00 2.780E+02 0.000E+00 0.000E+00 1.000E+05
2:) 3.593E-02 0.000E+00 0.000E+00 2.780E+02 0.000E+00 0.000E+00 1.000E+05
The numbers in the first column run from 1 to x (in this case 45) and then starts over at 1 lots of times. I want to move some of the columns to a separate file. The indexes of the columns I want to move is stored in the variable/array $selected_columns (in this case 2, 5 and 8) and the number of columns I want to move is stored in $number_of_columns (in this case 3).
I then want to create 45 files, one for the selected columns for all 1:), one for the selected columns for all 2:) and so forth. I want to make this as general as possible since both the number of columns and the number running from 1 to x will change. The number x is always known and the columns to extract are chosen by the user.
ORIGINAL QUESTION:
I have a string fetched by egrep. Then I want to print some of the columns (words) in that string. The position (column index) is known in a list in my bash script. Currently it looks like this:
line=$(egrep " ${i}:\)" $1)
for ((j=1; j<=$number_of_columns; j++))
do
awk $line -v current_column=${selected_columns[$j]} '{printf $(current_column)}' > "history_files/history${i}"
done
where number_of_columns is the number of columns that are to be printed and selected_columns contain the corresponding indexes of those columns. As an example number_of_columns = 3 and selected_columns = [2 5 8], so I want to print word number 2, 5 and 8 from the string line to the file history${i}.
I am not sure what is wrong, but this has been done with some trial and error. The current error is awk: cannot open 0.000E+00 (No such file or directory).
Any help is appreciated!
In:
$line holds the output of a grep, probably not something awk expects to see on it’s command line. Also,m this:
will cause you to overwrite the history file every time through the loop. I don’t know what you really wanted there.
You have a slew of other issues with your script, though. You said “As an example number_of_columns = 3 and selected_columns = [2 5 8], so I want to print word number 2, 5 and 8 from the string line to the file history${i}.”.
That’s trivial entirely in awk and you don’t need to do a “grep” outside of awk either, so you could just do the whole thing as:
If that doesn’t work for you, let’s fix THAT instead of trying to fix the original script. Sounds like you have enclosing loop outside of the above, chances are that could just be part of the awk script as well.
EDIT based on updated OP:
I’ve added lots of comments but let me know if you have questions:
By the way, I used the words “column” and “line” above for your benefit since you’re just learning, but FYI the awk terminology is actually “field” and “record”.