Powershell - 附加文件名,查找&替换,输出到目录

时间:2018-06-02 08:09:10

标签: powershell filenames find-replace

我有一些自动化任务,我想每天访问txt文件目录。这包括:

1.将文件名添加到txt文件的第一行

2.用分号替换制表符分隔的内容(查找和替换)

3.将文件保存到子目录

以下代码可用于查找&替换,但我无法将输出保存到其他目录,而是覆盖原始文件。是否有一个不同的命令允许我将输出保存到不同的目录?

(Get-Content "C:\Input\*.txt") -replace "`t", ";" | Set-Content "C:\Input\*.txt"

我目前有一个BAT项目1(附加文件名),但如果可以将其包装到Powershell脚本中,我认为这将是一种更清洁的做事方式。任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

对Vivek的答案略有修改,似乎有效。

#include <limits.h>
#include <stdio.h>

int main(void) {
    printf("\n");
    printf("             sizeof(int) -> %d\n", (int)sizeof(int));
    printf("    sizeof(unsigned int) -> %d\n", (int)sizeof(unsigned int));
    printf("        sizeof(long int) -> %d\n", (int)sizeof(long int));
    printf("   sizeof(long long int) -> %d\n", (int)sizeof(long long int));
    printf("\n");

    int b = 2147483647; // To show the maximum value of int type here is 2147483647
    printf("                   int b =  2147483647;\n");
    printf("                       b -> %d\n",b);
    printf("               sizeof(b) -> %d\n", (int)sizeof(b));
    printf("      sizeof(2147483647) -> %d\n", (int)sizeof(2147483647));
    printf("      sizeof(2147483648) -> %d\n", (int)sizeof(2147483648));
    printf("     sizeof(2147483648U) -> %d\n", (int)sizeof(2147483648U));
    printf("\n");

    unsigned int a = 2147483650;
    printf("          unsigned int a =  2147483650;\n");
    printf("                       a -> %u\n", a);
    printf("     sizeof(2147483650U) -> %d\n", (int)sizeof(2147483650U));
    printf("      sizeof(2147483650) -> %d\n", (int)sizeof(2147483650));
    printf("\n");

    unsigned int c = a+(-1);
    printf("          unsigned int c =  a+(-1);\n");
    printf("                       c -> %u\n", c);
    printf("               sizeof(c) -> %d\n", (int)sizeof(c));
    printf("                  a+(-1) -> %u\n", a+(-1));
    printf("          sizeof(a+(-1)) -> %d\n", (int)sizeof(a+(-1)));
#if LONG_MAX == 2147483647
    printf("         2147483650+(-1) -> %lld\n", 2147483650+(-1));
#else
    printf("         2147483650+(-1) -> %ld\n", 2147483650+(-1));
#endif
    printf(" sizeof(2147483650+(-1)) -> %d\n", (int)sizeof(2147483650+(-1)));
    printf("        2147483650U+(-1) -> %u\n", 2147483650U+(-1));
    printf("sizeof(2147483650U+(-1)) -> %d\n", (int)sizeof(2147483650U+(-1)));
    printf("\n");

    return 0;
}

答案 1 :(得分:0)

未经测试,但您可以试试这个 -

Get-ChildItem "C:\Input\" | where {$_.Name -match ".txt"} | % {((Get-Content $_) -replace "`t", ";") | Set-Content "DifferentDirectoryPath\$($_.Name)"}

如果您的Input文件夹包含您想要迭代的子文件夹,那么您可以使用它 -

Get-ChildItem "C:\Input\" -Recurse -Include "*.txt" | % {((Get-Content $_) -replace "`t", ";") | Set-Content "DifferentDirectoryPath\$($_.Name)"}