Update:
- It turns out that the real input file has no header line, whereas his answer assumes that it does.
I'm leaving the answer as-is, because the techniques of dealing with the header line may be of interest to future readers.
Your input file has a header line, which needs to be skipped (your bash
command would try to execute ipfs pin add
with the word of
from the header).
From each line, the second space-separated token must be extracted and passed to ipfs pin add
, which is what xargs -L1
in combination with bash -c '... $1'
implicitly does.
cat file.txt |
select -Skip 1 | # skip header line
% { # process each line
ipfs pin add (-split $_)[1] # Extract 2nd whitespace-separated token
}
Note:
On Windows, cat
is a built-in alias for PowerShel's Get-Content
cmdlet, on Unix-like platforms it refers to the standard utility, /bin/cat
.
select
is a built-in alias for Select-Object
, and, with lines of text as input,
Select-Object -Skip 1
is equivalent to tail -n +2
%
is a built-in alias for ForEach-Object
, which processes each input object via a script block ({ ... }
), inside of which the automatic $_
variable refers to the input object at hand.
The unary form of the -split
operator is used to split each line into whitespace-separated tokens, and [1]
extracts the 2nd token from the resulting array.
An alternative is to use the .Split()
.NET string method, as shown in a comment you made on your own question: in the case at hand, $_.Split(" ")[1]
is equivalent to (-split $_)[1]
However, in general the -split
operator is more versatile and PowerShell-idiomatic - see this answer for background information.
Note: I'm not familiar with ipfs
, but note that the docs for ipfs pin add
only talk about passing paths as arguments, not CIDs - it is ipfs pin remote add
that supports CIDs.
An alternative approach is to treat your input file as a (space-)delimited file and parse it into objects with Import-Csv
, which allows you to extract column values by column name:
Import-Csv -Delimiter ' ' file.txt |
ForEach-Object {
ipfs pin add $_.'IPFS CID'
}
Since ipfs pin add
supports multiple arguments, you can simplify and speed up the command as follows, using only one ipfs pin add
call:
ipfs pin add (Import-Csv -Delimiter ' ' file.txt).'IPFS CID'
This takes advantage of PowerShell's member-access enumeration feature and PowerShell's ability to translate an array of values into individual arguments when calling an external utility.
Note that, at least hypothetically, there's a platform-specific limit on the length of a command line that you could run into (which is something that only xargs
would handle automatically, by partitioning the arguments into as few calls as necessary).