简体   繁体   中英

how to add content for each line on certain character with powershell

I want to add : on text files on certain number of characters for example:

Original text file

ASDWEQRWEASDKLOEWQPEWQLJKEWQ
QWEKFKLWEJKJSDFJLKSADJAKLSJASDLAKJS
QWEJKLJSMCJSDJAIQEWJKLASDJA

Output file with add content of : on second and tenth position (character)

AS:DWEQRWEA:SDKLOEWQPEWQLJKEWQ
QW:EKFKLWEJ:KJSDFJLKSADJAKLSJASDLAKJS
QW:EJKLJSMC:JSDJAIQEWJKLASDJA

This will take a .txt file and insert : at position 2 & 10 on every line and output it to a .txt file.

Get-Content -Path C:\YourTextFile.txt `
    | ForEach-Object { $_.Insert(2,":").Insert(11,":") } `
    | Out-File -FilePath C:\YourOutPutFile.txt -Append

Use a regular expression:

(Get-Content 'C:\path\to\input.txt') -replace '^(.{2})(.{8})', '$1:$2:' |
    Set-Content 'C:\path\to\output.txt'

^(.{2})(.{8}) matches the first 2 and the next 8 characters at the beginning of a string ( ^ ), and captures them in two groups, so they can be referenced as $1 and $2 in the replacement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM