简体   繁体   English

如何使用PowerShell在某些字符上为每一行添加内容

[英]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. 这将获取一个.txt文件,并在每行的2和10位置插入: ,然后将其输出到.txt文件。

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. ^(.{2})(.{8})匹配字符串( ^ )开头的前2个字符和后8个字符,并将它们捕获为两组,因此可以在字符串中将它们分别称为$1$2 。替代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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