Powershell удалить строку из файла
to remove empty lines. But How I can remove them with '-replace' ?
My answer removes empty lines with the -replace comparison operator. Get-Content doesn't have a replace parameter, so I'm assuming you're looking for a way to do it with the operator.
13 Answers 13
See the original for some notes about the code. Nice :)
I think on balance I prefer (gc file.txt) | ? < -not $_.IsNullOrWhiteSpace() >| set-content file.txt because it expresses the intent more clearly, but it amounts to the same thing.
On brief glance, I do not seem to have the "IsNullOrWhiteSpace()" method on my strings. and. how could an instance method check for null? The posted answer works great though!
The IsNullOrWhiteSpace is a static method from System.String object the proper way to call it in PowerShell is as follow : [String]::IsNullOrWhiteSpace(
This piece of code from Randy Skretka is working fine for me, but I had the problem, that I still had a newline at the end of the file.
So I added finally this:
You can use -match instead -eq if you also want to exclude files that only contain whitespace characters:
Not specifically using -replace , but you get the same effect parsing the content using -notmatch and regex.
This worked like charm. I was attempting to remove VB6 comments from a file and this was the final command I used - (Get-Content -Path ".\vbXML.cls") -replace "\'.*$", "" -notmatch "^\s*$" | Out-File ".\vbXML.uncommented.cls" -Append
To resolve this with RegEx, you need to use the multiline flag (?m):
If you actually want to filter blank lines from a file then you may try this:
You can't do replacing, you have to replace SOMETHING with SOMETHING, and you neither have both.
You're talking apples and oranges. Remove and Replace are clearly different. What you have will basically work, but perhaps you are trying to rebuild the existing file but without the blanks. PS C:\> $text=get-content a.txt PS C:\> $text | where | out-file a.txt$_>
This will remove empty lines or lines with only whitespace characters (tabs/spaces).
file
PS /home/edward/Desktop> Get-Content ./copy.txt
[Desktop Entry]
Name=calibre Exec=~/Apps/calibre/calibre
Icon=~/Apps/calibre/resources/content-server/calibre.jpg
Type=Application*
Start by get the content from file and trim the white spaces if any found in each line of the text document. That becomes the object passed to the where-object to go through the array looking at each member of the array with string length greater then 0. That object is passed to replace the content of the file you started with. It would probably be better to make a new file. Last thing to do is reads back the newly made file's content and see your awesomeness.
(Get-Content ./copy.txt).Trim() | Where-Object | Set-Content ./copy.txt
Get-Content ./copy.txt
Для удаления пустых строк. Но как я могу удалить их с помощью «-replace»?
Мой ответ удаляет пустые строки с помощью оператора сравнения -replace . Get-Content не имеет параметра замены, поэтому я предполагаю, что вы ищете способ сделать это с помощью оператора.
См. оригинал для некоторых примечаний о коде. Хороший :)
Я думаю, что в целом я предпочитаю (gc file.txt) | ? < -not $_.IsNullOrWhiteSpace() >| set-content file.txt , потому что это более четко выражает намерение, но это то же самое.
На первый взгляд, у меня нет метода "IsNullOrWhiteSpace()" в моих строках. и. как метод экземпляра может проверить значение null? Опубликованный ответ отлично работает!
IsNullOrWhiteSpace — это статический метод из объекта System.String. Правильный способ вызова его в PowerShell выглядит следующим образом: [String]::IsNullOrWhiteSpace(
Этот фрагмент кода от Рэнди Скретки у меня работает нормально, но у меня была проблема, что у меня все еще была новая строка в конце файла.
Итак, я добавил, наконец, это:
Вы можете использовать -match вместо -eq, если вы также хотите исключить файлы, которые содержат только символы пробела:
Специально не используя -replace , но вы получаете тот же эффект при анализе содержимого с помощью -notmatch и регулярного выражения.
Это сработало как шарм. Я пытался удалить комментарии VB6 из файла, и это была последняя команда, которую я использовал — (Get-Content -Path ".\vbXML.cls") -replace "\'.*$", "" -notmatch "^\s*$" | Out-File ".\vbXML.uncommented.cls" -Append
Чтобы решить эту проблему с помощью RegEx, вам нужно использовать многострочный флаг (?m):
Если вы действительно хотите отфильтровать пустые строки из файла, вы можете попробовать следующее:
Это удалит пустые строки или строки, содержащие только пробельные символы (табуляции/пробелы).
Начните с получения содержимого из файла и обрежьте пробелы, если они есть в каждой строке текстового документа. Это становится объектом, переданным объекту where, чтобы пройти через массив, просматривая каждый элемент массива с длиной строки больше 0. Этот объект передается для замены содержимого файла, с которого вы начали. Вероятно, было бы лучше создать новый файл. Последнее, что нужно сделать, это прочитать содержимое только что созданного файла и увидеть, насколько он великолепен.
(Get-Content ./copy.txt).Trim() | Where-Object | Set-Content ./copy.txt
Get-Content ./copy.txt
Это удаляет завершающие пробелы и пустые строки из файла.txt.
Вы не можете заменить, вы должны заменить ЧТО-ТО на ЧТО-ТО, и у вас нет ни того, ни другого.
Просмотр содержимого дисков Windows PowerShell и управление хранящимися на них элементами аналогично управлению файлами и папками на физических дисках Windows. В этой статье описывается выполнение конкретных задач по управлению файлами и папками с помощью PowerShell.
Получение списка файлов и папок, содержащихся в папке
Извлечь все элементы непосредственно из папки можно с помощью командлета Get-ChildItem . Для отображения скрытых и системных элементов добавьте необязательный параметр Force. Например, эта команда отображает непосредственное содержимое диска C Windows PowerShell (которое совпадает с содержимым физического диска C Windows):
Эта команда выводит только элементы, содержащиеся на диске непосредственно, так же как и команда DIR оболочки Cmd.exe или команда ls оболочки UNIX. Для показа вложенных элементов необходимо также указать параметр -Recurse . (Время выполнения этой операции будет очень велико.) Для вывода всего содержимого диска C введите:
Командлет Get-ChildItem позволяет отфильтровать элементы с помощью параметров Path, Filter, Include и Exclude, но обычно осуществляется лишь фильтрация по имени. Сложную фильтрацию на основе других свойств элементов можно выполнить с помощью Where-Object .
Следующая команда находит все исполняемые файлы в папке Program Files, которые были в последний раз изменены после 1 октября 2005 г. и размер которых не менее одного мегабайта и не более десяти мегабайт:
Копирование файлов и папок
Копирование выполняется с помощью командлета Copy-Item . Следующая команда создает резервную копию C:\boot.ini в C:\boot.bak:
Если целевой файл уже существует, то попытка копирования завершается неудачей. Чтобы перезаписать имеющийся целевой файл, используйте параметр Force.
Эта команда работает, даже если целевой объект доступен только для чтения.
Так же выполняется и копирование папок. Эта команда копирует папку C:\temp\test1 в новую папку C:\temp\DeleteMe рекурсивно.
Можно также скопировать избранные элементы. Следующая команда копирует все файлы TXT, содержащиеся в папке C:\data , в папку C:\temp\text :
Для копирования элементов файловой системы можно использовать и другие средства. В Windows PowerShell по-прежнему работают команды XCOPY, ROBOCOPY и такие COM-объекты, как Scripting.FileSystemObject. Например, можно воспользоваться COM-классом Scripting.FileSystem сервера сценариев Windows для создания резервной копии файла C:\boot.ini в файле C:\boot.bak :
Создание файлов и папок
Создание новых элементов осуществляется одинаковым образом всеми поставщиками Windows PowerShell. Если поставщик Windows PowerShell поддерживает более одного типа элементов (например, поставщик Windows PowerShell FileSystem различает каталоги и файлы), необходимо указать тип элемента.
Эта команда создает папку C:\temp\New Folder :
Эта команда создает пустой файл C:\temp\New Folder\file.txt .
При использовании параметра Force с командой New-Item для создания папки, которая уже существует, она не перезапишет и не заменит папку. Будет просто возвращен имеющийся объект папки. Однако, если использовать New-Item -Force в уже имеющимся файле, файл будет полностью перезаписан.
Удаление всех файлов и папок, содержащихся в папке
Удалить вложенные элементы можно с помощью командлета Remove-Item , однако он потребует подтверждения удаления, если элемент сам что-нибудь содержит. Например, при попытке удаления папки C:\temp\DeleteMe , которая содержит другие элементы, Windows PowerShell предварительно предложит подтвердить удаление этой папки:
Если подтверждение для каждого вложенного элемента нежелательно, задайте параметр Recurse:
Подключение локальной папки как диска
Отобразить локальную папку можно с помощью команды New-PSDrive . Следующая команда создает локальный диск P: , корневым каталогом которого является локальный каталог Program Files, отображающийся только в сеансе PowerShell:
Как и при использовании сетевых дисков, диски, отображенные в Windows PowerShell, немедленно становятся доступными оболочке Windows PowerShell. Чтобы создать подключенный диск, отображающийся в проводнике, нужен параметр -Persist . Но с этим параметром можно использовать только удаленные пути.
Чтение текстового файла в массив
Одним из наиболее общих форматов хранения текстовых данных является файл, отдельные строки которого рассматриваются как отдельные элементы. Командлет Get-Content используется для чтения всего файла за один шаг, как показано далее:
Командлет Get-Content сразу рассматривает данные, считанные из файла, как массив с одним элементом на строку содержимого файла. Убедиться в этом можно, проверив свойство Length полученного содержимого:
Эта команда наиболее полезна для непосредственного ввода в Windows PowerShell информационных списков. Например, можно хранить в файле C:\temp\domainMembers.txt список имен компьютеров или IP-адресов по одному имени на каждую строку файла. Вы можете использовать командлет Get-Content , чтобы извлечь содержимое файла и поместить его в переменную $Computers :
Теперь переменная $Computers представляет собой массив, содержащий в каждом элементе имя компьютера.
Deletes the contents of an item, but does not delete the item.
Syntax
Description
The Clear-Content cmdlet deletes the contents of an item, such as deleting the text from a file, but it does not delete the item. As a result, the item exists, but it is empty. The Clear-Content is similar to Clear-Item , but it works on items with contents, instead of items with values.
Examples
Example 1: Delete all content from a directory
This command deletes all of the content from the "init.txt" files in all subdirectories of the SmpUsers directory. The files are not deleted, but they are empty.
Example 2: Delete content of all files with a wildcard
This command deletes the contents of all files in the current directory with the ".log" file name extension, including files with the read-only attribute. The asterisk (*) in the path represents all items in the current directory. The Force parameter makes the command effective on read-only files. Using a filter to restrict the command to files with the .log file name extension instead of specifying *.log in the path makes the operation faster.
Example 3: Clear all data from a stream
This example shows how the Clear-Content cmdlet clears the content from an alternate data stream while leaving the stream intact.
The first command uses the Get-Content cmdlet to get the content of the Zone.Identifier stream in the Copy-Script.ps1 file, which was downloaded from the Internet.
The second command uses the Clear-Content cmdlet to clear the content.
The third command repeats the first command. It verifies that the content is cleared, but the stream remains. If the stream were deleted, the command would generate an error.
You can use a method like this one to clear the content of an alternate data stream. However, it is not the recommended way to eliminate security checks that block files that are downloaded from the Internet. If you verify that a downloaded file is safe, use the Unblock-File cmdlet.
Parameters
Prompts you for confirmation before running the cmdlet.
Type: | SwitchParameter |
Aliases: | cf |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
This parameter is not supported by any providers installed with PowerShell. To impersonate another user, or elevate your credentials when running this cmdlet, use Invoke-Command.
Type: | PSCredential |
Position: | Named |
Default value: | Current user |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies, as a string array, strings that this cmdlet omits from the path to the content. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having PowerShell filter the objects after they are retrieved.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Forces the command to run without asking for user confirmation.
Type: | SwitchParameter |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies, as a string array, content that this cmdlet clears. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies the paths to the items from which content is deleted. Unlike the Path parameter, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell having PowerShell not to interpret any characters as escape sequences.
Type: | String [ ] |
Aliases: | PSPath, LP |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the paths to the items from which content is deleted. Wildcards are permitted. The paths must be paths to items, not to containers. For example, you must specify a path to one or more files, not a path to a directory. Wildcards are permitted. This parameter is required, but the parameter name ("Path") is optional.
Type: | String [ ] |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | True |
This Parameter is only available on Windows.
Specifies an alternative data stream for content. If the stream does not exist, this cmdlet creates it. Wildcard characters are not supported.
Stream is a dynamic parameter that the FileSystem provider adds to Clear-Content . This parameter works only in file system drives, and will clear the content of alternative data streams on both files and directories.
You can use the Clear-Content cmdlet to change the content of amy alternate data stream, such as Zone.Identifier . However, we do not recommend this as a way to eliminate security checks that block files that are downloaded from the Internet. If you verify that a downloaded file is safe, use the Unblock-File cmdlet.
This parameter was introduced in PowerShell 3.0. As of PowerShell 7.2, Clear-Content can clear the content of alternative data streams from directories as well as files.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: | SwitchParameter |
Aliases: | wi |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
None
You cannot pipe objects to Clear-Content .
Outputs
None
This cmdlet does not return any objects.
Notes
You can use Clear-Content with the PowerShell FileSystem provider and with other providers that manipulate content. To clear items that are not considered to be content, such as items managed by the PowerShell Certificate or Registry providers, use Clear-Item .
The Clear-Content cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type Get-PsProvider . For more information, see about_Providers.
Writes new content or replaces existing content in a file.
Syntax
Description
Set-Content is a string-processing cmdlet that writes new content or replaces the content in a file. Set-Content replaces the existing content and differs from the Add-Content cmdlet that appends content to a file. To send content to Set-Content you can use the Value parameter on the command line or send content through the pipeline.
If you need to create files or directories for the following examples, see New-Item.
Examples
Example 1: Replace the contents of multiple files in a directory
This example replaces the content for multiple files in the current directory.
The Get-ChildItem cmdlet uses the Path parameter to list .txt files that begin with Test* in the current directory. The Set-Content cmdlet uses the Path parameter to specify the Test*.txt files. The Value parameter provides the text string Hello, World that replaces the existing content in each file. The Get-Content cmdlet uses the Path parameter to specify the Test*.txt files and displays each file's content in the PowerShell console.
Example 2: Create a new file and write content
This example creates a new file and writes the current date and time to the file.
Set-Content uses the Path and Value parameters to create a new file named DateTime.txt in the current directory. The Value parameter uses Get-Date to get the current date and time. Set-Content writes the DateTime object to the file as a string. The Get-Content cmdlet uses the Path parameter to display the content of DateTime.txt in the PowerShell console.
Example 3: Replace text in a file
This command replaces all instances of word within an existing file.
The Get-Content cmdlet uses the Path parameter to specify the Notice.txt file in the current directory. The Get-Content command is wrapped with parentheses so that the command finishes before being sent down the pipeline.
The contents of the Notice.txt file are sent down the pipeline to the ForEach-Object cmdlet. ForEach-Object uses the automatic variable $_ and replaces each occurrence of Warning with Caution. The objects are sent down the pipeline to the Set-Content cmdlet. Set-Content uses the Path parameter to specify the Notice.txt file and writes the updated content to the file.
The last Get-Content cmdlet displays the updated file content in the PowerShell console.
Example 4: Use Filters with Set-Content
You can specify a filter to the Set-Content cmdlet. When using filters to qualify the Path parameter, you need to include a trailing asterisk ( * ) to indicate the contents of the path.
The following command set the content all *.txt files in the C:\Temp directory to the Value empty.
Parameters
Specifies that the content should be read as a stream of bytes. This parameter was introduced in PowerShell 6.0.
A warning occurs when you use the AsByteStream parameter with the Encoding parameter. The AsByteStream parameter ignores any encoding and the output is returned as a stream of bytes.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Prompts you for confirmation before running the cmdlet.
Type: | SwitchParameter |
Aliases: | cf |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
This parameter is not supported by any providers installed with PowerShell. To impersonate another user, or elevate your credentials when running this cmdlet, use Invoke-Command.
Type: | PSCredential |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the type of encoding for the target file. The default value is utf8NoBOM .
Encoding is a dynamic parameter that the FileSystem provider adds to Set-Content . This parameter works only in file system drives.
The acceptable values for this parameter are as follows:
- ascii : Uses the encoding for the ASCII (7-bit) character set.
- bigendianunicode : Encodes in UTF-16 format using the big-endian byte order.
- bigendianutf32 : Encodes in UTF-32 format using the big-endian byte order.
- oem : Uses the default encoding for MS-DOS and console programs.
- unicode : Encodes in UTF-16 format using the little-endian byte order.
- utf7 : Encodes in UTF-7 format.
- utf8 : Encodes in UTF-8 format.
- utf8BOM : Encodes in UTF-8 format with Byte Order Mark (BOM)
- utf8NoBOM : Encodes in UTF-8 format without Byte Order Mark (BOM)
- utf32 : Encodes in UTF-32 format.
UTF-7* is no longer recommended to use. As of PowerShell 7.1, a warning is written if you specify utf7 for the Encoding parameter.
Type: | Encoding |
Accepted values: | ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 |
Position: | Named |
Default value: | UTF8NoBOM |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as *.txt . Wildcard characters are permitted. The Exclude parameter is effective only when the command includes the contents of an item, such as C:\Windows\* , where the wildcard character specifies the contents of the C:\Windows directory.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies a filter to qualify the Path parameter. The FileSystem provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the FileSystem filter language in about_Wildcards. Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Forces the cmdlet to set the contents of a file, even if the file is read-only. Implementation varies from provider to provider. For more information, see about_Providers. The Force parameter does not override security restrictions.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt" . Wildcard characters are permitted. The Include parameter is effective only when the command includes the contents of an item, such as C:\Windows\* , where the wildcard character specifies the contents of the C:\Windows directory.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies a path to one or more locations. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences.
Type: | String [ ] |
Aliases: | PSPath, LP |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
The string representations of the input objects are concatenated to form the output. No spaces or newlines are inserted between the output strings. No newline is added after the last output string.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Returns an object that represents the content. By default, this cmdlet does not generate any output.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the path of the item that receives the content. Wildcard characters are permitted.
Type: | String [ ] |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | True |
This Parameter is only available on Windows.
Specifies an alternative data stream for content. If the stream does not exist, this cmdlet creates it. Wildcard characters are not supported.
Stream is a dynamic parameter that the FileSystem provider adds to Set-Content . This parameter works only in file system drives.
You can use the Set-Content cmdlet to create or update the content of any alternate data stream, such as Zone.Identifier . However, we do not recommend this as a way to eliminate security checks that block files that are downloaded from the Internet. If you verify that a downloaded file is safe, use the Unblock-File cmdlet.
This parameter was introduced in PowerShell 3.0.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the new content for the item.
Type: | Object [ ] |
Position: | 1 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: | SwitchParameter |
Aliases: | wi |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
You can pipe an object that contains the new value for the item to Set-Content .
Outputs
None or System.String
When you use the PassThru parameter, Set-Content generates a System.String object that represents the content. Otherwise, this cmdlet does not generate any output.
Читайте также: