When I had to move from Linux to Windows (I'm still using Linux in a VM) because of my company policies, I lacked super useful Linux tools such as grep, cut, sort, uniq and sed until I found PowerShell equivalent of them. However, every time I needed one of them, I had to search. So, I decided to put them together here for you.
Let's create a dummy text file which is "fruits.txt" as follows
cat (Get-Content)
PS C:\> Get-Content fruits.txt
orange,orange
apple,green
grapes,purple
banana,yellow
apple,red
peach,orange
pear,yellowish
apple,green
grep (Select-String)
PS C:\> Select-String -Path fruits.txt -Pattern "apple"
fruits.txt:2:apple,green
fruits.txt:5:apple,red
fruits.txt:8:apple,green
grep -e (multiple match)
PS C:\> Select-String -Path fruits.txt -Pattern "apple|banana"
fruits.txt:2:apple,green
fruits.txt:4:banana,yellow
fruits.txt:5:apple,red
fruits.txt:8:apple,green
grep -v
PS C:\> Select-String -Path fruits.txt -Pattern "apple" | ?{$_ -notmatch 'green'}
fruits.txt:5:apple,red
grep -A 3 -B 1 (1 line before and 3 lines after with matched line)
PS C:\> Select-String -Path fruits.txt -Pattern "banana" -Context 1, 3
fruits.txt:3:grapes,purple
> fruits.txt:4:banana,yellow
fruits.txt:5:apple,red
fruits.txt:6:peach,orange
fruits.txt:7:pear,yellowish
grep -R *.py (Recursive search for files with a specific extension. eg. *.py)
PS C:\> Get-ChildItem -Path .\ -Filter *.py -Recurse -File -Name | ForEach-Object {Select-String -Path ([string]$_) -Pattern "banana"}
cut (cut -d ',' -f 1)
Unlike in Linux, field index is starting from zero in PowerShell.
PS C:\> Get-Content fruits.txt | ForEach-Object { ([string]$_).Split(",")[0] }
orange
apple
grapes
banana
apple
peach
pear
apple
sort
You can also use just "sort" instead of "Sort-Object"
PS C:\> Get-Content fruits.txt | Sort-Object
apple,green
apple,green
apple,red
banana,yellow
grapes,purple
orange,orange
peach,orange
pear,yellowish
uniq
Like in Linux, we need to sort before get unique.
PS C:\> Get-Content fruits.txt | Sort-Object | Select-String -Pattern "apple"
apple,green
apple,green
apple,red
Now, we can use "Get-Unique"
PS C:\> Get-Content fruits.txt | Sort-Object | Select-String -Pattern "apple" | Get-Unique
apple,green
apple,red
sed
PS C:\> ((Get-Content -Path fruits.txt) -replace 'peach','apricot')
orange,orange
apple,green
grapes,purple
banana,yellow
apple,red
apricot,orange
pear,yellowish
apple,green
If you would like to save replaced version to a file like "new_fruits.txt"
PS C:\> ((Get-Content -Path fruits.txt) -replace 'peach','apricot') | Set-Content -Path new_fruits.txt
Bonus (recursive file searching with a specific extension)
PS C:\> Get-ChildItem -Path .\ -Filter *.ipynb -Recurse -File -Name
Hope this helps!
Comments