【问题标题】:How to add file name to (beginning of) a text file?如何将文件名添加到文本文件(开头)?
【发布时间】:2019-06-28 19:11:03
【问题描述】:

对于超过 800 个文件,我需要将文件名中的信息包含在文本文件(实际上是 .md 文件)的内容中。

文件名始终具有相同的结构,例如0000-title-text-1-23.md;只有1-23 部分发生了变化(这就是我需要的信息)。

在编写脚本方面我是新手,但我发现这对于 PowerShell 来说应该是一件容易的事——但我并没有让它按我想要的方式工作。最接近的是什么:

Get-Childitem "C:\PATH\*.md" | ForEach-Object{
   $fileName = $_.BaseName
   Add-Content -Path .\*.md -Value $fileName
   }

但这会添加目录中的所有文件名,而不仅仅是文件本身的文件名。

我做错了什么?

【问题讨论】:

  • 你很接近。使用 $_ 是您的 .md 文件。您可以在Add-Content 中使用它来指定应该获取内容的文件

标签: powershell


【解决方案1】:

使用这段代码做你想做的事,

  • 它将获取文件名的最后 2 部分和
  • 将其放在文件内容的开头。
Get-Childitem "C:\PATH\*.md" | ForEach-Object{
   $fileNameParts = ($_.BaseName).split('-')
   $info = $fileNameParts[-2] + '-' + $fileNameParts[-1]
   $info + (Get-Content $_ -Raw) | Set-Content $_
}

【讨论】:

    【解决方案2】:

    虽然它确实将内容添加到文件末尾,但类似这样的东西会起作用:

    #Get all the .txt or .md files in your location
    Get-ChildItem -Filter "*.txt" | Foreach-Object{
    
        #Get the base name of the file
        $baseName = $_.BaseName
    
        #Split the base name
        $array = $baseName -Split '-'
    
        #Put the third and fourth element in the array into a separate variable
        #This will be added to the file
        $addToFile = $array[3] + '-' + $array[4]
    
        #Add the $addToFile variable to the file
        Add-Content $_.FullName -Value $addToFile
    }
    

    【讨论】:

    • 代码中有一个错字:它写的是“Filer”而不是“File”。但即使修正了那个,我也没有得到任何结果(文件末尾没有任何新内容)。
    • @Jopie 抱歉打错了,已更正:) 您是否更改了 .txt 过滤器,否则它将无法在您的 .md 文件上运行?
    • 好点,我确实忘记了。现在它起作用了! (虽然 Shadowfax 的解决方案仍然更适合我的情况。不过感谢提供更多解释性代码 - 它帮助我完成了掌握 PowerShell 的任务!)
    • @Jopie 同意,Shadowfax 给出了更合适的答案 :) 祝您探索愉快!
    猜你喜欢
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 2011-12-10
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多