從txt檔案中提取數字

從txt檔案中提取數字

我在 txt 檔案中有一個很大的聯絡資訊清單。我需要從這樣的結構中取得電話號碼:

例子

我需要輸出僅包含文字中的數字,例如:

  • 4149611000
  • 4143620851
  • 3605966100
  • 3096949898
  • ETC。

cmd中的什麼指令可以解決這個問題?

答案1

太長了;博士perl -lne 'print $1 while /(\d{10})/g' filenames.txt ...


$ cat n.txt
aaaa 0123456789 bbbb
apple banana cucumber
9876543210 ccc ccc ccc
ppp qqq 12345 rrr sss
$ perl -lne 'print $1 if /(\d{10})/' n.txt
0123456789
9876543210

如果每條線路可以有多個電話號碼並且您確實需要所有電話號碼:

$ echo double 1111111111 number 2222222222 here >> n.txt
$ perl -lne 'print $1 while /(\d{10})/g' n.txt
0123456789
9876543210
1111111111
2222222222

如果電話號碼始終是第五個逗號分隔字段,您可以使用

$ perl -F, -lne 'print $F[4]' m.txt 
PHONE
1234567890
0987654321

注意 perl 有基於 0 的索引(0,1,2 而非 1,2,3)

或使用更簡單的工具:

$ cut -d, -f5 m.txt
PHONE
1234567890
0987654321

以上是在 Windows 10 下使用 WSL 完成的,但本機 Windows Perl 可用於 Windows 10 命令提示字元。像這樣:

C> perl -lne "print $1 while /(\d{10})/g" n.txt
0123456789
9876543210
1111111111
2222222222

幾乎可以肯定有一種方法可以在 powershell 中執行此操作(儘管可能需要更多打字)

答案2

使用 Powershell,嘗試以下 cmdlet:

Get-Content -Path C:\path\to\yourfile.txt | Select-String "\d{10}" -AllMatches | ForEach {$_.Matches} | Select Value

或者

Select-String -Path "C:\path\to\yourfile.txt" -Pattern "\d{10}" -AllMatches | Select -ExpandProperty Matches | Select Value

這將僅顯示 10 位長度的數字。如果你想在文件中輸出:

Get-Content -Path C:\path\to\yourfile.txt | Select-String "\d{10}" -AllMatches | ForEach-Object {$_.Matches} | Select Value | Out-File output.txt

相關內容