This keeps the formatting:
Main Topics
Browse All TopicsHave a formatted text like the following:
Type test.txt
XXXX =
(SRV =
(ADDRESS = (PROTOCOL = TST)(HOST = AAAA01-TST)(PORT = 0000))
(ADDRESS = (PROTOCOL = TST)(HOST = AAAA02-TST)(PORT = 1111))
(BBBB = yes)
(CONN_INFO =
(SVR = SHA)
(SVC_NAME = TEST1)
)
)
If I use the 'for' loop to process the text, it will assign the left. How to preserve the spaces and formats? For example, I did it with the following:
for /F %%a in (test.txt) do @echo %%a >>test1.txt
Type test1.txt
You will see the left assigned text, which I do not want it.
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
The * tells the FOR command to use all tokens, and seeing as you are not defining any delimeters by which to split the content into tokens, it will echo the lines literally, which includes white space.
Usually you would be using the FOR command to split each line into separate tokens which could be separated by eg. a space, a comma, or some other character, and you would specify what delimeter to treat as the point you want to split the lines into chunks.
It may get complicated if your example is going to be part of a larger batch file that DOES need to split the lines into tokens and get the data stored in each token (variable), but you can always ask if that is the case.
Another tip that you may have noticed. Try to place the redirection >> immediately after the %%variable you are echoing. Sometimes it makes not difference, but sometimes it includes an unwanted space after whatever is being echoed if you do leave a space.
Example test.txt:
67890,12345
You want to combine that into 1234567890 and output it to test1.txt.
for /f "tokens=1-2 delims=," %%a in (test.txt) do @echo %%b%%a >> test1.txt
would leave a trailing space after the number in your text file, but (note the %%b%%a>>):
for /f "tokens=1-2 delims=," %%a in (test.txt) do @echo %%b%%a>> test1.txt
would eliminate the trailing space after the number.
Though the question is answered by BillDL, it would be a good idea to show what you want to do while processing. Your example looks very much like an TNSNames.ora file (Oracle Network definition). Parsing in the batch will be hard, as already mentioned by Bill.
If you want to replace a host name without changing anything else, an external tool like chgstr might be a better choice.
BillDL, thank you so much for indeeep analysis. Only question left is for blank line. Which condition should be set to catch a blank line? For example,
type test.txt
This is a test.
Test
This is the last line.
----------
I tried to catch it by
if "%%a"=="" @echo.>>test1.txt
but it failed to do so.
Qlemo, thanks for your suggestion. I need to work out this issue.
I
You're welcome jl66. I had a feeling that you would be wanting to do a whole lot more with the file. Qlemo's method of using the /N switch in the FIND command to create line numbers in square brackets is exactly the method I have used often before to do just the same thing as you need. And here was me thinking I had a clever little personal trick of my own ;-)
I've just spent 2 whole hours (I know... I should have known better) experimentally trying to crack this one again... hoping to find something new.
Qlemo
Call yourself a programmer!.... tut, tut, tut.... Your code fails to produce the required output
BillDL
Call yourself a programmer!.... tut, tut, tut.... Your code fails to produce the goodies too.
jl66
Call yourself lucky!! I'm a programmer! Yippee!! Check out the code below....
@echo off
copy nul test1.txt >nul
for /f "tokens=1,* delims=[]" %%a in ('type test.txt^|find /n /v ""') do (
echo.%%b>>test1.txt
)
Oh, by the way, the code handles the following:
Lines with leading spaces
Lines with leading tabs
Blank lines (just Carriage-Return and Linefeed)
Blank lines (just spaces)
Blank lines (just tabs)
Any other line
@echo off
copy nul test1.txt >nul
for /f "tokens=1,* delims=[]" %%a in ('type test.txt^|find /n /v ""') do (
echo.%%b>>test1.txt
)
Qlemo
The proof is in the eating of the pudding, as they say.
Why not test BOTH batch files using the attached text file and then compare their outputs.
T0T0'S BATCH FILE
@echo off
copy nul output >nul
for /f "tokens=1,* delims=[]" %%a in ('type file.txt^|find /n /v ""') do (
echo.%%b>>output
)
QLEMO'S BATCH FILE
@echo off
(for /f "tokens=1* delims=]" %%A in ('find /n /v "" ^< file.txt') do @echo %%B) > output
BILLDL'S BATCH FILE
@echo off
for /f "tokens=* delims=" %%a in (test.txt) do @echo %%a>> test1.txt
JL66
By the way, my batch file could just as well have been written as follows:
@echo off
(for /f "tokens=1,* delims=[]" %%a in ('type file.txt^|find /n /v ""') do echo.%%b)>output
Please take the trouble to test all three batch files and ONLY when you are satisfied my code delivers the goods should you consider closing this question and awarding ALL 500 points to me with a grade A.
Qlemo should NOT recieve a share of the points (nor should BillDL as their codes do not work properly) because Qlemo had an opportunity to re-test his code at this stage however, he says his code works (it does not) and he asks, why shouldn't it? - well, if Qlemo ran his code I am sure the answer to that question would become apparent.
Thank you in advance. I eagerly await my 500 x Grade A points !!!
Paul,
I think you misunderstood some of the principles here: Experts collaborate to get a solution, not compete with each other.
And it is common sense to prove something is not working, not only assuming it.
Well, I'm terribly sorry (for you), having to say that all three codes work the same (as soon as BillDL's code is adapted to your file naming). I do not dare to say my code is correct, but that it works with the example.
BTW, telling askers into how they have to accept is drawing attention of the Moderators, as it is considered inappropriate. Since I'm loosing my temper (based on your attitude), I might help a bit with that part.
1) Thanks to everyone very much. Everyone's inputs are valuable to me and I will properly weigh it as best as I can.
2) This is a platform to exchange ideas and I am learning from your experts. Meanwhile I throw my issues, which may trigger the friendly debates which is needed, and provide the opportunity your experts are learning from each other. That is all about. Take easy and be happy.
Everyone
I think this is a clear example of how it is impossible, within the written word alone, to portray a tongue-in-cheek and twinkle in the eye jesting with others no matter how many smileys are used, unless the reader is on exactly the same wave length with, and has previously had the benefit of watching and listening to, the writer in person.
We all have our own personalities that may or may not become apparent the longer we read each others' postings. Some people are fiercely competitive and strive to outwit others in any way possible, and for those people the competitive nature is probably what has made them excel in certain activities, just like an athlete can't give up the need to beat the opposition or risk losing focus. It's sometimes hard to know at what point the desire to win has exceeded what is deemed to be excessive and counter-productive. Perhaps Tonya Harding could guide us on that issue ;-)
Did that tonge-in-cheek jibe come across as intended?
In context with the intentons within this question, all three of our batch files output exactly the same results. An example file was given without a fuller explanation as to why it needed to be parsed. The file does not contain blank lines, fancy characters, or any other potential impediments that would cause my original batch file to fail. In my batch example I did not intend to preempt such complications, but did warn that other difficulties could be encountered dependent on what the file was being parsed for.
I agree that it is probably better at the outset to eliminate as many potential "DOS" traps as is possible, but if we were to get really pedantic about covering all likely events, we would be driving about all year round with 75% anti-freeze in the windscreen washer, snow chains on the tyres, swimming trunks, sun-block cream and a spear gun in case we ended up on a beach, a climbing rope and carabiners in case we ended up on a mountain pass, a kite in case it got windy, a Liebigs Condenser in case we ended up somewhere with polluted water and got thirsty, a stun gun and hand-held siren in case we were attacked by a bear/shark/lion/camel, and a collection of Snickers bars and jerky in case we got stuck in the middle of nowhere in a sandstorm/snowstorm/earthq
Now, that's just plain ridiculous, but I hope my humour came through ;-)
BillDL, Qlemo etc...
I'm sorry guys. I refuse to be slagged down when I know I'm right.
There are 2 main reasons why my code works as it does. I would have thought you'd have spotted it.
Please have the courtesy of checking your code before making wild statements like "all three codes work the same" and that I should "prove something is not working and not just assume it".
Well, I thought I did prove it - by posting all three codes in my last comment. I'm surprised neither of you could find the time to check your own codes against mine if only to reassure yourselves. A good programmer would have done.
UNLESS there is something very different about my DOS and yours then perhaps you would kindly look at a dump taken from my DOS box and correct me if I am wrong. Please pay particular attention to the first few lines and then the results at the end.
NOTE: I have modelled this test on the data file provided by the asker.
SCREEN DUMP (taken directly from my DOS box)
==========================
C:>copy con FILE.TXT
This is a test.
Test
This is the last line.
^Z
1 file(s) copied.
C:>copy con QLEMO.BAT
@echo off
(for /f "tokens=1* delims=]" %%A in ('find /n /v "" ^< FILE.TXT') do @echo %%B) >QLEMO.TXT
^Z
1 file(s) copied.
C:>copy con BILLDL.BAT
@echo off
for /f "tokens=* delims=" %%a in (FILE.TXT) do @echo %%a>> BILLDL.TXT
^Z
1 file(s) copied.
C:>copy con T0T0.BAT
@echo off
copy nul T0T0.TXT >nul
for /f "tokens=1,* delims=[]" %%a in ('type FILE.TXT^|find /n /v ""') do (
echo.%%b>>T0T0.TXT
)
^Z
1 file(s) copied.
C:>qlemo
C:>billdl
C:>t0t0
C:>========================
C:>type qlemo.txt
This is a test.
Test
ECHO is off.
This is the last line.
C:>========================
C:>type billdl.txt
This is a test.
Test
This is the last line.
C:>========================
C:>type t0t0.txt
This is a test.
Test
This is the last line.
C:>========================
C:>
t0t0
>>> "Please have the courtesy of checking your code before making wild statements like 'all three codes work the same'." <<<
I did comparison of the outputs from all three batch files using the example text, and that includes variances in white space. The output files are exactly the same for the example given. I don't really care if the outputs differ when using a different source file, and I haven't taken the time to even check, because it wasn't within the context of the question. I don't intend to begin arguing who is right and who is wrong. All batch files do as intended given the criteria presented.
I gave you the benefit of the doubt by assuming that you had a twinkle in your eye when you started laying down challenges, but I take it back now and have to say that your insistance of always being right is quite annoying at times. To demand points and instruct the asker to dismiss sugestions made by other experts is not only patronising to the asker, but as insulting to the other experts as being kicked in the nuts from behind.
Bill
BillDL
I'm a programmer. That's what I do. I don't do it for a job. I do it out of interest. And I take it quite seriously.
I'm here to provide solutions to questions which I find intellectually amusing. And fo course, I'm competing for points. There! I've said it!
When working alongside other experts who rank high in their field of expertise, I don't think it's patronising to expect the same level of commitment to detail.
Even in your last comment, you still maintain all three codes produce the same results. Even though it's obvious they don't. To you, this is a game. It's not about you being so short-sighted you fail see the wood through the trees, nor about you being ignorant to the point of failing to acknowledge the facts presented in my previous comment.
For your information, when comparing the results of our codes, I DID used only the source data provided by the asker.
I have provided a screen dump of my test runs.
I'm not going to argue this one with you because this is no longer turning out to be a scientific discussion.
I'll tell you what, you can keep the sodding points and continue to behave like children.
Ehem. Just to stay technically sober:
qlemo
If you cast your mind back to http:#25713832 you'll notice the asker posted the following in his comment as a way of testing for blank lines:
Only question left is for blank line .... For example:
This is a test.
Test
This is the last line.
Obviously, like BillDL, you only see what you want to see. Furthemore, you state:
>>"The missing point after echo in http:#25713901 must have been lost by cut&waste somehow"
Oh, come on... I could probably swallow that if the dot had been right at the end of the line however, that's not the case here. Are you really sating your cut&paste just happened to 'somehow' lose a 'dot' from:
@echo.%%B
but not from either of these:
test.txt
test1.txt
You are a fibber. You made it quite clear that retaining empty lines required:
>>"adding something to each line and removing it afterwards"
Obviously, you were referring to line numbers added by FIND's /N switch. There was never any mention of a dotted echo - something which I myself stumbled upon quite by accident and after two hours of mucking about with DOS.
You talk about proof (http:#25721713), in http:#25720893, you say you tested your code with various examples - pity you didn't include an example output file to back up this claim - because that's the difference between providing proof and not providing proof. I don't think you tested your code at all.
Qlemo, we're experts, and it's our responsibility to deliver working solutions. It shouldn't be about guess-work or assumptions - as you put it. Sure, there have been times I've submitted untested code myself however, I make it clear in my comment the code is untested.
You say experts should 'collaborate'.... well, I'm not seeing much collaboration right at this moment. If I were working for a company where my job depended on the delivery of working code, I'd be foolish to want to collaborate with someone who fails to acknowledge he could be wrong.
Qlemo, you answer far more questions than I do. So does BillDL. I can't understand why you can't just eat humble pie and let this one go.
It's no longer about the points. It's about standing my ground on principles and fairness.
jl66
You must be a bit fed up by now with your question having been transformed into a circus. Hopefully your question has been answered and you will be inclined to close it out. How you do so is entirely up to you. I'm not really too concerned by which comment(s) you choose to accept. Don't take that as being apathetic to you or to your question though. If you got what you needed from the question, then that's really what matters in the end, and what Experts-Exchange should be all about.
Regards
Bill
Just for the sake of completeness, the following is the code I used to test. I don't know why my code in http:#25713901 differs. This code will retain spaces and empty lines (the previously posted code will echo a ECHO IS OFF instead of each empty line).
Sorry for late response. I carefully tested the solutions. Everyone's exceeds my expectation, so each of you should be awarded full 500 points. However, all I have is only 500. I have to split them.
You may think I am greedy. The issue is that I have multiple blocks like my original question seperated by blank lines. I must process them. Next time I will create a new ticket for my new question. Sorry for that.
1) Bill answered it early for my original question correctly.
2) Qlemo and t0t0 are real sharp "programmers/solution providers". I made a test file combined my two test files together and add one more blank line in the bottom. Here is hte results I got with fc:
M:\>fc test.txt output
Comparing files test.txt and OUTPUT
FC: no differences encountered
M:\>fc test1.txt test.txt
Comparing files test1.txt and TEST.TXT
***** test1.txt
***** TEST.TXT
*****
It seems t0t0's solution is a little bit better this time.You both deserve 500*500 points. But this time I am going to select Bill as an solution. Sorry for both of you. Appreciate for your great ideas and outstanding expertise.
>>"It seems t0t0's solution is a little bit better this time."
What do you mean, "it seems a little better"? It's the ONLY solution that actually worked! (http:#25720032)
>>"But this time I am going to select Bill as an solution."
Here are the three programs BillDL submitted. Please state which one you have selected as a solution:
(A) http:#25712843 - @echo off
for /f "tokens=* delims=" %%a in ('type test.txt') do @echo %%a>> test1.txt
(B) http:#25712847 - @echo off
for /f "tokens=* delims=" %%a in (test.txt) do @echo %%a>> test1.txt
(C) http:#25712887 - @echo off
for /f "tokens=1-2 delims=," %%a in (test.txt) do @echo %%b%%a>> test1.txt
So, you won't be using my solution at all then, nor Qlemos?.... I only ask because if your source file contains spaces then none of BillDL's programs will work properly.
>>"Qlemo and t0t0 are real sharp "programmers/solution providers"
50% of this statement is highly questionable! But you failed to spot this.
>>"The silent bird catches the worm" - or was it "early"?
This has nothing to do with "silence" or "birds" however, I'm not too sure about "worrms" though.
>>"Bill answered it early for my original question correctly"
Oh, well that solves it then!!
Thank you jl66.
I feel embarrassed that you had to sit out and endure a load of petty nonsense about why everyone else was wrong except for one.
I am pleased that you did get the solution to the follow-on part of your question that helps you with the blank line issue though. Don't worry about feeling the need to ask a separate question for a follow-on query that is clearly still very much in context with the originally asked one.
It's perfectly reasonable to ask for a batch file to be extended, reworked, revised, etc. to accommodate some issues that have come to light after the original question was posed, but which weren't specifically indicated as criteria at the outset. It's totally unreasonable, however, being made to feel as if you are being bullied into acceptance of one person's solution.
You don't have to apologise to anyone in any way about not having posted a full block of text. How were you to anticipate that it may have been an important issue? You certainly are not responsible for the aftermath. Sometimes questions are asked and solutions are reached in separate episodes. That's just a fact of life.
t0t0
Could you please stop plastering my name all over your infantile comments. I provided two variants of one batch file, plus one further batch example and a full explanation of the THEORY behind each of them. This was in direct response to the ORIGINALLY ASKED QUESTION. Read that again please - THE ORIGINAL QUESTION. The ORIGINAL source text, NOT the example in the follow-up comment. I then stepped back out of the question when Qlemo provided a suggestion to address that follow-up issue about blank lines.
You just can't seem to get this part through your head, can you?
Look, you are at it again in your very last comment, which I regard as overtly challenging to jl66, and and yet another attempt to stab others between the shoulder blades:
>>> "... if your source file contains spaces then none of BillDL's programs will work properly." <<<
Who the hell ever said that my batch file would work on a source containing blank lines? I certainly didn't, and nor did jl66.
By harping on like a lunatic you are angering me and insulting the intelligence of jl66, who has provided some very clear and concise reasons why he made his final choice, a decision that he should not feel intimidated about doing.
Thank you again jl66 :-)
Bill
Business Accounts
Answer for Membership
by: kyodaiPosted on 2009-10-31 at 21:19:08ID: 25712593
Afaik /F just return the first word of each line, it should actually cut off everything past the lines first word. /F is good to read out variables or paths from a line separated values file, but as you noticed, spaces and tabs are a no go. I dont know what exactly you are trying to do here, but maybe it is not solvable with batch. If you cant rewrite the text file so everything is in one line without spaces or tabs you may consider using another method, i.e. an external program, a visual basic script or some sel-coded helper program.