I am totally new to unix and need some help regarding grep command

I have an output file with 7 parameter values S1, S2..., S7. How can I use grep command to extract only the values and write them as an array to a new file, which I want to plot later.

<<<<< Function evaluation summary (APPROX_INTERFACE_1): 1808 total (1808 new, 0 duplicate)
<<<<< Best parameters          =
                      3.3500000000e+02 S1
                      1.0357218750e+00 S2
                      7.2046250000e+01 S3
                      7.2872921875e+01 S4
                      5.7405507812e+01 S5
                      5.0000054687e+01 S6
                      2.3999984375e+02 S7
<<<<< Best objective function  =
  • 1
    What operating system are you using? Can we assume your grep has the -o flag? How about the -P flag? Also, please edit your question and show us the output you are expecting from this input. What are the 7 parameter values? Is Function a parameter? Is APPROX_INTERFACE_1 one? How about 1808? How can we identify the parameters?
    – terdon
    Commented Dec 5, 2022 at 16:08

2 Answers 2


Grep is a line selection tool.

grep ' S.$' your.txt 

will give you the lines with the 7 values.

If you need to trim the values from each line you can use cut:

grep ' S.$' yout.txt |cut -d ' '  -f23

Use 23 if you have 22 spaces in the beggining of each line.

AWK will be a good alternative to both grep and cut.


If we can be sure that what we want is the first field of every line whose second field is a S followed by a number, we can do:

$ awk '$2~/^S[0-9]$/{print $1}' data

If you want those as values in an array, do:

array=( $(awk '$2~/^S[0-9]$/{print $1}' data) )

And if you want them in a new file, do:

awk '$2~/^S[0-9]$/{print $1}' data > new.data
  • Thanks. how can I put the values in an array and then store the array in a new file ? Commented Dec 5, 2022 at 16:47
  • @MandeepSingh I don't understand why you would want to do both. If you really, really need to, just use array=( $(awk '$2~/^S[0-9]$/{print $1}' data) ) and then run printf '%s\n' "${array[@]}" > newFile. But why not just redirect to a file directly?
    – terdon
    Commented Dec 5, 2022 at 16:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .