Line breaks and spaces in text files disappear in bat

Asked 2 years ago, Updated 2 years ago, 85 views

In bat, I wrote something to replace the characters in a file, but line breaks and spaces disappear.
Please tell me how to solve this problem.

@echo off
Copy rem source file to temp
copy%~n1.tex"%~n1"_temp.tex

Remove rem source file
del "% to n1.tex"

setlocal enabled delayed expansion
for /f "delims="%%ain(%~n1_temp.tex)do(
  set line = %%a
  set line=!line:.=.!
  set line=!line: , =, !
  echo!line!>>% to n1.tex
)
endlocal

windows batch-file

2022-09-30 20:19

2 Answers

I don't know the details of line breaks and spaces disappear, so I'm not sure if it applies to all the data, but I think it's because of the way echo is written.

Replace strings with .bat batch files in windows


because of echo ·It is assumed that there were no empty lines
·Echo off is output for lines with only half-width spaces

Additionally, the output of substitution for environment variables will apply to the following:

By Command/echo

It's good to write some kind of symbol right after echo.Most symbols are fine, but the most common ones are ./: and so on.
However, if echo. is used, it is not allowed to include the letter = between !! and !!.
Now, you can use one of the following symbols after echo: ;=.

On the contrary, the output may be blanked.

Batch files|Read text files line by line (full version?)

6. Bonus: It might be good to enclose echo in parentheses

Based on the above, please try the echo line as follows.
Please try various things such as whether or not it has parentheses and changing the symbols used.

(echo=!line!)>>% to n1.tex

Furthermore, I'm Nan, but FOR/F is the default value of eol= and the line starts with semicolon
The line is treated as a comment line and skipped, which seems difficult to avoid.

FOR/F How to extract and execute files line by line with its 1=FOR statement - Windows Command Prompt (bat,cmd)

Other than that, if you specify setlocal enabled delayed expansion, the target file name will be restricted.
Notes to avoid trial and error in batch files

@sayuri-san I think it would be better to try PowerShell or use commands such as sed or awk(gawk) that specialize in editing and string processing.
GNU utilities for Win32


2022-09-30 20:19

Additional information.If you use sed for bat, perhaps the easiest way is to introduce git bash.
MinGW will also be included during setup, so you can use it normally from the command prompt.
https://gitforwindows.org/


2022-09-30 20:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.