管理人Kのひとりごと

デジモノレビューやプログラミングや写真など

LinuxでPowershell試してみた

LinuxでPowershell試してみました。

検証環境

CentOS on Docker@Windowsで実施しました。

# 実行環境
PS C:\Users\hoge> docker --version
Docker version 20.10.8, build 3967b7d

Powershell on CentOS@Docker環境の構築

Dockerfile

FROM centos:centos7

RUN yum -y update && yum -y install curl

# Register the Microsoft RedHat repository
RUN curl https://packages.microsoft.com/config/rhel/7/prod.repo | tee /etc/yum.repos.d/microsoft.repo

# Install PowerShell
RUN yum install -y powershell

ビルド

# Dockerfileのある場所で実施
docker build -t centos7_pwsh .

実行

PS C:\Users\hoge\Documents\dockerfiles\centos7_pwsh> docker run --rm -it centos7_pwsh pwsh --version
PowerShell 7.2.0

PS /tmp/docs> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      7.2.0
PSEdition                      Core
GitCommitId                    7.2.0
OS                             Linux 5.4.72-microsoft-standard-WSL2 #1 SMP Wed Oct 28 23:40:43 UTC 2020
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

過去記事の処理を実行

Powershellで複数ファイルの中身を一括置換

www.k-hitorigoto.online
同じ結果が得られました

PS /tmp/docs> Get-ChildItem . |`  # ← 途中改行はLinuxでも「`」で行けた
>>  %{$_.name; echo ======; cat $_.Name; echo ""}
one.txt
======
first
second
third

three.txt
======
first
second
third

two.txt
======
first
second
third


PS /tmp/docs> Get-ChildItem . |`
>>  %{ $replaced = $(Get-Content $_.Name) -replace "first","FIRST"; $replaced > $_.Name }

PS /tmp/docs> Get-ChildItem . |`
>> %{$_.name; echo ======; cat $_.Name; echo ""}
one.txt
======
FIRST
second
third

three.txt
======
FIRST
second
third

two.txt
======
FIRST
second
third

Powershellでfindしてxargsしてgrep

www.k-hitorigoto.online
同じ結果が得られました

PS /tmp/docs> Get-ChildItem . | ?{ !$_.PSIsContainer}| %{ Select-String -Path $_.FullName -Pattern F}

one.txt:1:FIRST
three.txt:1:FIRST
two.txt:1:FIRST

PS /tmp/docs> find ./ -type f | xargs grep F
./two.txt:FIRST
./one.txt:FIRST
./three.txt:FIRST