0
$\begingroup$

Consider a file file.txt having the form

# First line is a grid of y; Starting from second line: first number is a, second is temperature, next is set of numbers is corresponding to f(y) on the grid
0.000000e+00    0.000000e+00    0.000000e+00    2.500000e-01    5.000000e-01
0.100000e+00    0.000000e+01    0.010000e+02    2.500000e-02    5.000000e-02

How to convert it to a form

0.000000e+00    0.000000e+00    0.000000e+00    2.500000e-01    5.000000e-01
0.100000e+00    0.000000e+01    0.010000e+02    2.500000e-02    5.000000e-02

which can be interpreted as numerical data?

$\endgroup$
  • $\begingroup$ If you know how many lines you need to skip, there is the HeaderLines options for many of the import formats. $\endgroup$ – Lukas Lang Nov 12 '19 at 12:19
1
$\begingroup$

To just take out the first line

str = "# First line is a grid of y; Starting from second line: first number is a, second is temperature, next is set of numbers is corresponding to f(y) on the grid
0.000000e+00    0.000000e+00    0.000000e+00    2.500000e-01    5.000000e-01
0.100000e+00    0.000000e+01    0.010000e+02    2.500000e-02    5.000000e-02"

(*Method 1*) StringReplace[str, Shortest[head__] ~~ "\n" ~~ rest__ :> rest]
(*Method 2*) #1 <> "\n" <> #2 & @@ Rest@StringSplit[str, "\n"] == %

"0.000000e+00 0.000000e+00 0.000000e+00 2.500000e-01 5.000000e-01 0.100000e+00 0.000000e+01 0.010000e+02 2.500000e-02 5.000000e-02"

True

If there are multiples lines in the header, such as

str = "# First line is a grid of y;
# Starting from second line:
# first number is a
# second is temperature
# next is set of numbers is corresponding to f(y) on the grid
0.000000e+00 0.000000e+00 0.000000e+00 2.500000e-01 5.000000e-01
0.100000e+00 0.000000e+01 0.010000e+02 2.500000e-02 5.000000e-02";

StringReplace[str, ("#" ~~ Shortest[__] ~~ "\n") .. ~~ rest__ :> rest]

"0.000000e+00 0.000000e+00 0.000000e+00 2.500000e-01 5.000000e-01 0.100000e+00 0.000000e+01 0.010000e+02 2.500000e-02 5.000000e-02"

And if there are comments within the data, or actually in any case,

str = "# First line is a grid of y;
# Starting from second line:
# first number is a
# second is temperature
# next is set of numbers is corresponding to f(y) on the grid
0.000000e+00 0.000000e+00 0.000000e+00 2.500000e-01 5.000000e-01
# test comment
0.100000e+00 0.000000e+01 0.010000e+02 2.500000e-02 5.000000e-02";

StringReplace[str, ("#" ~~ Shortest[__] ~~ "\n") :> ""]

"0.000000e+00 0.000000e+00 0.000000e+00 2.500000e-01 5.000000e-01 0.100000e+00 0.000000e+01 0.010000e+02 2.500000e-02 5.000000e-02"

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.