Extract characters from a text file in Linux


I have a very basic question. I have the following text file (cdrag.txt) and I want to extract only the value (number) that is just after Cd :

forceCoeffs forceCoeffs execute:
    Cm       : -3.99664 (pressure: -4.01246 viscous: 0.01582)
    Cd       : 2.13648  (pressure: 2.13673  viscous: -0.000249648)
    Cl       : 1.18858  (pressure: 1.18672  viscous: 0.00185425)
    Cl(f)    : -3.40235
    Cl(r)    : 4.59093


I tried with the command:

cat cdrag | grep  "Cd       : " | cut -d':' -f2  

But this command shows me on the screen "2.13648 (pressure"), that is, what is between the two points, and not just the value 2.13648, which is my goal.

Note: this numerical value is not always the same

Any idea how I could do it? Thank you very much!

asked by CristinaHP 16.06.2018 в 11:36

2 answers


I would do this:

cat cdrag | grep "Cd       : " | cut -d':' -f2  | cut -d' ' -f2

If the format is strict and the spaces will not vary in your input .

Now, if you need something a little more robust in terms of format variation, consider using a small script in awk , or in python .

answered by 16.06.2018 в 14:48

There is something that is not very clear, I understand that the fielchero is of several lines and that they begin with the Cd, Cl, Cm, etc. And what you ask is only for this particular file, because you only need one more thing, remove what is after the number you are looking for. To what you already have you add the cut for space

cat cdrag | grep "Cd:" | cut -d ':' -f2 | cut -d '' -f2

To the result, you cut them separated by '' and you stay with the second field because the first one is the blank space in front of the number

answered by 16.06.2018 в 14:49