Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
Maybe a combination of Import and StringReplace. – anderstood Aug 10 '14 at 6:43
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. – george2079 Aug 10 '14 at 14:29
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. – m_goldberg Aug 10 '14 at 14:46
up vote 2 down vote accepted

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"

and saving again your changes with

Export[file, f]

and reimport for verifying

Import[file, "CSV"]
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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