Измерения массива превысили поддерживаемый диапазон

On a Windows 10 command line, creating a tar archive with “special” characters (e.g. extended latin) in the path of the archive itself results in errors.

To be slightly more exact, a quick sample suggests that characters above unicode code point 255 seem to fail. That is Latin Extended-A and above.

Note: This is about the path of the tar archive itself. The files inside the archive (a.k.a. members) all have “simple” ASCII paths.

Note: out-of-the-box Windows 10 includes bsdtar from libarchive, located in c:\Windows\System32\tar.exe.

For example, tar -c -f Ā.tar foo creates an archive called A.tar, instead of Ā.tar.

Similarly, if I have an existing archive called Ā.tar, then tar -t -f Ā.tar yields

tar: Error opening archive: Failed to open ‘A.tar’

and something like tar -c -f Δ.tar foo fails altogether with

tar: Failed to open ‘?.tar’

Question: What could be the cause, and is there a fix or workaround?

  • the issue was reproduced in cmd, powershell, and (git-)bash (explicitly calling c:\Windows\System32\tar.exe in bash)
  • the issue does not arise with GNU tar, as bundled with git-for-windows (also tested in cmd, powershell, and bash)
  • the issue does not arise on Ubuntu Linux (calling bsdtar after installing libarchive-tools)
  • similar problems arise if the tar members have characters above code point 255 in their path, even if using the PAX format (this does appear to extend to GNU tar as well)
  • default codepage is 437, but changing codepage, e.g. chcp 65001, makes no difference
  • moreover, not all characters from codepage 437 seem to work either
  • other programs work just fine with the same “special” characters, e.g. notepad Δ.txt
  • libarchive #587, #1629, …
  • Can the UTF-8 code page identifier (65001) be different on other computers?
  • …

4.2 – 2024-04-11

General Cmdlet Updates and Fixes

  • Revert “Adjust PUT method behavior to POST one for default content type in WebCmdlets” (#21049)
  • Fix regression with Get-Content when -Tail 0 and -Wait are both used (#20734) (Thanks @CarloToso!)
  • Fix Get-Error serialization of array values (#21085) (Thanks @jborean93!)
  • Fix a regression in Format-Table when header label is empty (#21156)

Engine Updates and Fixes

  • Revert the PR [#17856] (Do not preserve temporary results when no need to do so) (#21368)
  • Make sure the assembly/library resolvers are registered at early stage (#21361)
  • Handle the case that Runspace.DefaultRunspace is null when logging for WDAC Audit (#21344)
  • Fix PowerShell class to support deriving from an abstract class with abstract properties (#21331)
  • Fix the regression when doing type inference for $_ (#21223) (Thanks @MartinGC94!)

Build and Packaging Improvements

Bump to .NET 8.0.4

  • Revert analyzer package back to stable
  • Update SDK, deps and cgmanifest for 7.4.2
  • Revert changes to packaging.psm1
  • Update PSResourceGet version from 1.0.2 to 1.0.4.1 (#21439)
  • Verify environment variable for OneBranch before we try to copy (#21441)
  • Remove surrogateFile setting of APIScan (#21238)
  • Add dotenv install as latest version does not work with current Ruby version (#21239)
  • Multiple fixes in official build pipeline (#21408)
  • Add back 2 transitive dependency packages (#21415)
  • Update PSReadLine to v2.3.5 for the next v7.4.x servicing release (#21414)
  • PowerShell co-ordinated build OneBranch pipeline (#21364)

SHA256 Hashes of the release artifacts

Need to extract a TAR file (.tgz) on your Windows system? TAR files are commonly used for bundling multiple files in Unix-based systems, but you can easily extract them in Windows as well. In this guide, we will show you how to extract TAR files (.tgz) using various tools available on Windows. Our step-by-step instructions will help you quickly and efficiently unpack these files, making the contents accessible on your Windows computer.

:/>  Windows как запустить exe через консоль

Table of Content

Quick Highlights About TAR File Format

  • The File Format Name comes from the Tape Archive Term
  • The TAR File Format is used to write data on Magnetic Tapes.
  • TAR Files can be used for Archiving as well as for Compressing.
  • It has many directories included along with the content.

Method 1: Extract TAR Files Using Command Prompt

1--Open-Commnad-Prompt

Command: tar -xvzf <TAR-FIle-Location> -C <New-Location>

2--Execute-Command

Congratulation! You have successfully Extracted TAR Files on Windows using Command Prompt.

If you want to extract the TAR Files on your local device, then have any third-party application on your device. There are many third-party applications present like 7-Zip or WinZip, etc. Using any one of those, you can Open TAR FIle on Windows

You have to download & install the third-party apps on the device. Later, select any one TAR file & it will be directly converted to the simple folder structure. To open any TAR Folder inside the new one, select it again.

3--Third-Party-App

Hooray! You now have one third-party application installed on the device to Unzip Linux TAR Format on Windows

Now, if you want to get your job reduced to some folds, there is another option present. It is to Extract the TGZ File Online. There are many present on the internet that can be used for successful conversion.

You have to select the TAR File & want to choose the operation. If you want, it will convert the TAR File to RAR file which is the Native File Compressor for Windows. Or it can directly extract the files on your desktop.

4--Converter

  1. Execute the command tar -xvzf <TAR-FIle-Location> -C <New-Location>
  2. Find the New File in the saved location.

How do I Unzip a TGZ file in Linux?

  1. Open Terminal Window.
  2. Execute the command tar -xvzf <TAR-FIle-Location> -x
  3. The File will be extracted.

How to Convert the TAR File to an RAR File?

To convert TAR File to RAR File, there are numerous online converters present. You have to change the operation on the website & select the TAR File from the Local Machine. Wait for the process to be completed & the new RAR File will be ready to download.

Please to comment…

Introduction

Imagine being in a scenario where a file of type .tar.gz lands in your Azure Blob Storage container. This file, when uncompressed, yields a collection of individual files. The trigger event for the arrival of this file is an Azure function, which springs into action, decompressing the contents and transferring them into a different container.

In this context, a team may instinctively reach out for a robust library like SharpZipLib. However, what if there is a mandate to accomplish this without external dependencies? This becomes a reality with .NET 7.

In .NET 7, native support for Tar files has been introduced, and GZip is catered to via System.IO.Compression. This means we can decompress a .tar.gz file natively in .NET 7, bypassing any need for external libraries.

This post will walk you through this process, providing a practical example using .NET 7 to show how this can be achieved.

Native TAR Support

As of .NET 7, the System.Formats.Tar namespace was introduced to deal with TAR files, adding to the toolkit of .NET developers:

  • System.Formats.Tar.TarFile to pack a directory into a TAR file or extract a TAR file to a directory
  • System.Formats.Tar.TarReader to read a TAR file
  • System.Formats.Tar.TarWriter to write a TAR file
:/>  Максимум ядер процессора и памяти в конфигурации windows почему не нужно настраивать

These new capabilities significantly simplify the process of working with TAR files in .NET. Lets dive in an have a look at a code sample that demonstrates how to extract a .tar.gz file natively in .NET 7.

A Simple Example In .NET 7

Below is an example demonstrating the extraction of a .tar.gz file natively in .NET 7 in a simple console app to extract the contents of a .tar.gz file to a directory


































































tarFilePath = Path.ChangeExtension(sourceTarGzFilePath, );




(FileStream originalFileStream = File.OpenRead(sourceTarGzFilePath))

(FileStream decompressedFileStream = File.Create(tarFilePath))

(GZipStream decompressionStream = GZipStream(originalFileStream, CompressionMode.Decompress))







(FileStream tarStream = File.OpenRead(tarFilePath))

(TarReader tarReader = TarReader(tarStream))


((entry = tarReader.GetNextEntryAsync().Result) != )

(entry.EntryType TarEntryType.SymbolicLink TarEntryType.HardLink TarEntryType.GlobalExtendedAttributes)





entry.ExtractToFileAsync(Path.Combine(targetDirectory, entry.Name), ).Wait();










You can also find this on GitHub Gist.

Wrapping Up

The introduction of System.Formats.Tar in .NET 7 marks a significant milestone for developers dealing with .tar.gz files. It provides us with the ability to decompress these file types natively, without relying on external libraries. This functionality is a game-changer as it reduces complexity, minimizes external dependencies, and enhances the versatility of .NET applications.

The new namespace System.Formats.Tar, along with the established System.IO.Compression, effectively handle TAR and GZip files. This considerably simplifies the process, making the .NET environment more self-contained and versatile.

Пытался загрузить датасет corus taiga, загружая по этим командам:

wget https://linghub.ru/static/Taiga/retagged_taiga.tar.gz
tar -xzvf retagged_taiga.tar.gz

Однако получил ошибку:

PS C:\Users\egor4> wget https://linghub.ru/static/Taiga/retagged_taiga.tar.gz wget : Измерения массива превысили поддерживаемый диапазон.
строка:1 знак:1
+ wget https://linghub.ru/static/Taiga/retagged_taiga.tar.gz
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Invoke-WebRequest], OutOfMemoryException + FullyQualifiedErrorId : System.OutOfMemoryException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Windows 10 pro x64, 16GB

Алексей Р's user avatar

2 золотых знака8 серебряных знаков20 бронзовых знаков

Xelbor _'s user avatar

Команда wget в Powershell является синонимом Invoke-Webrequest, который, по умолчанию, сохраняет загруженные в оперативную память. Файл, что вы пытаетесь загрузить, содержит 92 GB данных. Вы же в вопросе указали, что на вашем ПК установлено лишь 16 GB, из которых Powershell может использовать еще меньше.

Для загрузки этого файла убедитесь в том, что у вас достаточно свободного места на диске, и выполните:

wget -OutFile path\to\file https://linghub.ru/static/Taiga/retagged_taiga.tar.gz

Стас's user avatar

2 золотых знака9 серебряных знаков26 бронзовых знаков

Это команды для линукса.
Для винды нужно

  • либо выполнить их в WSL,
  • либо установить wget.exe и tar.exe (ищите GnuWin32)
  • либо скачать файл вручную через браузер и вместо tar использовать 7z 🙂

ESkri's user avatar

9 бронзовых знаков

По мере того как программное обеспечение становится более мощным, а медиа наполняется всё бо́льшим объёмом данных, размеры файлов продолжают расти с экспоненциальной скоростью. В результате становится все более распространённым хранение и отправка файлов в сжатых форматах, в том числе и .tar.gz.

Однако сжатие и извлечение этих файлов не всегда интуитивно. В этом руководстве мы предоставим основные инструкции по распаковке файлов .tar.gz в Linux-системах.

Что такое файлы .tar и .tar.gz?

Файл .tar – это собрание файлов, сжатых в один файл или архив. Сокращённое от “Tape ARchive” (архив ленты) название “TAR” связано со временем, когда файлы хранились на магнитных ленточных накопителях.

К счастью, для использования и извлечения файлов .tar вам не нужно быть компьютерным техником 1960-х годов, и современные архивы .tar вообще не имеют никакого отношения к старым компьютерам.

Точно так же, как и более знакомые всем архивы .zip, файлы .tar сжимают большие файлы в один пакет, что упрощает их хранение, отправку или перемещение. В результате это стало довольно распространённым расширением файлов как для пакетов программного обеспечения, так и для многих других ресурсов.

В отличие от .zip у .tar есть несколько дополнительных функций, которые делают его лучшим форматом сжатия для определённых файлов и приложений. Основное отличие состоит в том, что архив .zip состоит из множества индивидуально сжатых файлов, в то время как архив .tar сжат как один пакет при том, что заархивированные файлы остаются несжатыми. Другими словами, файл .zip представляет собой коллекцию сжатых файлов, а файл .tar – сжатую коллекцию файлов.

:/>  Bat имена файлов с пробелами

Что касается формата .tar.gz, то это – файл .tar, который был сжат или “запакован” с помощью утилиты gzip. Именно её использование для сжатия является причиной добавления двойного расширения к файлу – .gz.

Хотя gzip и является наиболее распространённой утилитой для уменьшения объёма архивов, это не единственный вариант. Как вы можете предположить, использование другой утилиты сжатия для файла .tar приведёт к другому двойному расширению – .tar.br (Brotli), .tar.bz2 (bzip2), .tar.zst (zstd) и так далее.

Разные утилиты сжатия могут требовать разных методов для извлечения и распаковки файлов. В данном случае мы сосредоточимся на файлах .tar.gz.

Работа с архивами .tar.gz

Для распаковки файлов .tar.gz в Linux-системах применяется утилита tar. Команда для извлечения содержимого архива выглядит следующим образом:

$ tar -xvf yourarch.tar.gz

Данная команда извлекает (-x) указанный архивный файл (-f) (в данном случае yourarch.tar.gz) в текущую директорию. Таким же образом утилита tar работает с архивами, упакованными при помощи других форматов сжатия, например, .tar.bz2. Опция -v не является обязательной и позволяет выводить информацию о процессе и в данной команде выводит извлекаемые из архива файлы в окно терминала.

Чтобы извлечь файлы не в текущий каталог, а какую-либо другую директорию, следует применять опцию -C. Вот так, например, выглядит команда для разархивирования содержимого yourarch.tar.gz в директорию /tmp/yourdir:

$ tar -xf yourarch.tar.gz -C /tmp/yourdir

Часто бывает полезно перечислить содержимое файла .tar.gz без непосредственно распаковки архива. В такие моменты пригодится опция -t, которая выведет список имён файлов, содержащихся в архиве. Например:

$ tar -tf yourarch.tar.gz
Просмотр содержимого tar-архива - Как извлекать и разархивировать файлы .tar.gz

Если вам нужно распаковать не весь архив, а лишь извлечь некоторые его элементы (файлы или каталоги), просто перечислите их, разделяя пробелами:

$ tar -xf yourarch.tar.gz yourdir2 yourfile3 yourdir33
Извлечение из tar-архива выборочных файлов и каталогов

Обратите внимание, что вышеприведённая команда выдаст ошибку, если в ней не будет указано точное имя файла или директории, соответствующее содержащимся в архиве.

Ошибка при не правильном указании имени файла и каталога при выборочном извлечении

Вы также можете извлечь .tar.gz непосредственно из стандартного входного потока stdin, передав его утилите tar. При этом в самой утилите необходимо использовать параметр распаковки -z. Например, следующая команда извлечёт содержимое архива, расположенного по адресу http://X.X.X.X/yourarch.tar.gz, где используется команда wget, которая передаётся утилите tar:

$ wget -c http://X.X.X.X/yourarch.tar.gz -O - | sudo tar -xz
Пример передачи стандартного входного потока утилите tar при распаковке архива, расположенного удалённо

Утилита gzip

Для создания архивов .tar применяются разнообразные утилиты сжатия, в том числе и gzip. Данная утилита является одним из самых доступных и популярных вариантов для создания сжатых файлов. К тому же, она встроена в большинство дистрибутивов Linux и macOS.

Формат команды создания архива выглядит как:

$ gzip yourarch.tar

А при помощи опции -d вы можете легко распаковать полученный файл .tar:

$ gzip -d yourarch.tar

Если вы хотите сохранить исходный файл после сжатия, вам следует использовать параметр -c для вывода сжатого файла в другой с сохранением оригинала:

$ gzip -c yourarch.tar > newyourarch.tar.gz
Сжатие архива с сохранением оригинального файла - Как извлекать и разархивировать файлы .tar.gz

Для того, чтобы упаковать каждый из файлов в директории, применяется опция -r. Например, следующая команда создаёт архивы всех файлов, находящихся внутри каталога yourdir, а также внутри всех вложенных директорий внутри него:

$ gzip -r yourdir

Следующая команда, в свою очередь, производит декомпрессию всех файлов в директории yourdir, включая вложенные каталоги:

$ gzip -dr yourdir