1

I have a text file filled with characters:

ABCABCABCABC

...and with a script (Batch, VBS, Powershell, anything simple for Windows really) am trying to automatically add a new line for every instance of a certain character, in this case the letter A, so the output would then appear as such:

ABC
ABC
ABC
ABC

How can this be accomplished with any of the scripting tools I mentioned above?

Much appreciated, thanks a bunch!

5 Answers5

6

Powershell:

(get-content c:\somedir\inputfile.txt) -replace 'A',"`nA" | set-content c:\somedir\outputfile.txt
mjolinor
  • 66,130
  • 7
  • 114
  • 135
  • Updated code to show example use for file processing. For very large files you may need to adjust that to use -readcount and a foreach-object loop to conserve memory. – mjolinor Mar 21 '13 at 18:52
2

If you can use SED GOOGLE GNUSED

sed s/A/\nA/g <yourfile >resultfile
Magoo
  • 77,302
  • 8
  • 62
  • 84
1

Notepad++

This is just a find and replace if you have notepad++ installed on your computer
(http://notepad-plus-plus.org/download/v6.3.1.html)

Open your text file, press Ctrl H to get Find & Replace

Select Search Mode as Extended or Regular expression

Find A

Replace \nA

Saju
  • 3,201
  • 2
  • 23
  • 28
0

Windows batch:

@echo off
setlocal enabledelayedexpansion

echo contents of oldfile.txt:
type oldfile.txt
echo;

del newfile.txt
for /f "usebackq delims=" %%I in ("oldfile.txt") do (
    set "str=%%I" && set "str=!str:A=,A!"
    for %%x in (!str!) do (>>"newfile.txt" echo %%x)
)

echo contents of newfile.txt:
type newfile.txt

Example output:

C:\Users\me\Desktop>test.bat
contents of oldfile.txt:
ABCABCABCABCABC

contents of newfile.txt:
ABC
ABC
ABC
ABC
ABC

Here's more info on splitting a string in batch.

Community
  • 1
  • 1
rojo
  • 24,000
  • 5
  • 55
  • 101
0

JScript:

var fso = new ActiveXObject("Scripting.FileSystemObject");
var read = fso.OpenTextFile("oldfile.txt", 1, 2);
var write = fso.CreateTextFile("newfile.txt", true);
var str = read.ReadAll();
write.Write(str.replace(/A/g,'\nA').replace(/^\n/m,''));
read.Close(); write.Close();

The second .replace removes the first new line if it occurs as the first character of the text. Save this script with a .js extension and execute it with cscript filename.js.

rojo
  • 24,000
  • 5
  • 55
  • 101