3
$\begingroup$

I have a text file, its content is(for example):

 388, 399, 100 
*Nset, nset=All, internal, generate
  1,  48,  1
*Elset, elset=All, internal, generate
  1,  35,   1
** Section:solidplane
*Solid Section, elset=All, material="rigid body"
*End Instance

Now I want use Mathematica read the above content and modify it; for example,

(1) I want the number "48 (3rd line)" to change to number"388 (1st line)",

(2) I want the word "All (4th line)" to change to word "Whole",

How can I realize it?

So the output is:

 388, 399, 100
*Nset, nset=All, internal, generate
  1,  388,   1
*Elset, elset=Whole, internal, generate
  1,  35,   1
** Section:solidplane
*Solid Section, elset=All, material="rigid body"
*End Instance

I have used the function "ReadList" but failed... Hope someone can help me

$\endgroup$
3
  • $\begingroup$ Maybe a combination of Import and StringReplace. $\endgroup$
    – anderstood
    Aug 10, 2014 at 6:43
  • 1
    $\begingroup$ you should keep everything that you don't change in string format start with Import[file,{"Text","Lines"}]. Then you need to cook up the appropriate string operations to make the desired changes. $\endgroup$
    – george2079
    Aug 10, 2014 at 14:29
  • $\begingroup$ I would not use Mathematica for this. For a one-off situation, I would edit the file in a capable text editor, say, emacs. If there were a lot of files to edit, I would turn to a scripting language such as Python or Ruby. $\endgroup$
    – m_goldberg
    Aug 10, 2014 at 14:46

1 Answer 1

2
$\begingroup$

Here my proposition

Maybe the best format in this case is "CSV" (also "Table" would be interesting )

You'll have to customize myPath and "material.txt"

myPath = NotebookDirectory[];
file = ToFileName[myPath, "material.txt"]
f = Import[file, "CSV"]

once the file is loaded, it appears without quotes in Mma (I saved it previously in the actual directory for this example) you may get

{{388, 399, 100}, {"*Nset", " nset=All", " internal", 
  " generate"}, {1, 48, 1}, {"*Elset", " elset=All", " internal", 
  " generate"}, {1, 35, 
  1}, {"** Section:solidplane"}, {"*Solid Section", " elset=All", 
  " material=\"rigid body\""}, {"*End Instance"}}

you can access now e.g. 399 in line=1, item=2 (you don't have to write line or item, this is just for clear explanation)

f[[line = 1, item = 2]]

so doing your questions 1) and 2) with

f[[line = 3, item = 2]] = f[[line = 1, item = 1]]
f[[line = 4, item = 2]] = "elset=Whole"
f

and saving again your changes with

Export[file, f]

and reimport for verifying

Import[file, "CSV"]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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