尋找並提取字串中的文字

尋找並提取字串中的文字

我想從資料檔案中尋找字串 Pattern 內的文本,並使用 shell 或 AppleScript 將它們提取到文本列表中。

XML 中的一個範例:

node file="source_files/ (var1) .mp3"

HMTL 的另一個例子:

src="http:// (example.com) /dir/ (var2) .txt"

期望的輸出:

1.1 source_files/example1.mp3
1.2 source_files/blah.blah

2.1 http://example.com/dir/example2.txt
2.2 http://example.com/dir/blah.blah

我的問題是,我將如何搜尋、尋找和提取文字檔案中之前、之後或兩者都具有特定字元模式的所有字串系列?

答案1

使用以下grep命令怎麼樣:

grep -Po '(?<==")[^"]+(?=")'

這將提取出現在等號後面的雙引號字串。這是在行動中:

user@host:~$ echo 'node file="source_files/example1.mp3"' \
| grep -Po '(?<==")[^"]+(?=")'

source_files/example1.mp3

user@host:~$ echo 'src="http://example2.com/dir/example2.txt"' \
| grep -Po '(?<==")[^"]+(?=")'

http://example2.com/dir/example2.txt

答案2

grep -F 'node file="source_files/example1.mp3"'

grep -F 'src="http://example2.com/dir/example2.txt"'

相關內容