提取两个字符串之间的多个文本实例

提取两个字符串之间的多个文本实例

我想提取包含 Spotify 图表结果的文本文件中两个字符串之间的文本

文本文件提取:

{"tracks":[{"date":"2014-12-14","country":"TW","track_url":"https:\/\/play.spotify.com\/track\/34gCuhDGsG4bRPIf9bb02f","track_name":"Thinking Out Loud","artist_name":"Ed Sheeran","artist_url":"https:\/\/play.spotify.com\/artist\/6eUKZXaKkcviH0Ku9w2n3V","album_name":"x","album_url":"https:\/\/play.spotify.com\/album\/1xn54DMo2qIqBuMqHtUsFd","artwork_url":"http:\/\/o.scdn.co\/300\/646e9619750dfa3d1eadbbea959dc6f528a9109e","num_streams":51672,"window_type":"weekly","percent_male":58,"percent_age_group_0_17":4,"percent_age_group_18_24":45,"percent_age_group_25_29":25,"percent_age_group_30_34":12,"percent_age_group_35_44":7,"percent_age_group_45_54":1,"percent_age_group_55_plus":6},

我要提取的文本是曲目名称。上述文本文件的所需输出:

1 Thinking Out Loud
2 xxx
3 xxx

为了实现这一点,我想使用sednl命令来提取字符串之间的文本

"track_name":"       and
   ",

...并将结果输出到另一个文本文件

答案1

如果您有 GNU grep,则可以使用与 perl 兼容的正则表达式。由于环视断言,这很方便:

grep -oP '(?<=track_name).*?(?=,)' filename

答案2

这是一个示例正则表达式,它与您提供的输入相匹配并为您提供所需的输出。使用此方法,我们使 sed 对每一行执行搜索+替换,如果该行包含 track_name 和逗号,则仅用中间部分替换整行。然后我们只打印匹配的行 (p)。

[me:~]$ cat work/tmp/example.txt 
{"tracks":[{"date":"2014-12-14","country":"TW","track_url":"https:\/\/play.spotify.com\/track\/34gCuhDGsG4bRPIf9bb02f","track_name":"Thinking Out Loud","artist_name":"Ed Sheeran","artist_url":"https:\/\/play.spotify.com\/artist\/6eUKZXaKkcviH0Ku9w2n3V","album_name":"x","album_url":"https:\/\/play.spotify.com\/album\/1xn54DMo2qIqBuMqHtUsFd","artwork_url":"http:\/\/o.scdn.co\/300\/646e9619750dfa3d1eadbbea959dc6f528a9109e","num_streams":51672,"window_type":"weekly","percent_male":58,"percent_age_group_0_17":4,"percent_age_group_18_24":45,"percent_age_group_25_29":25,"percent_age_group_30_34":12,"percent_age_group_35_44":7,"percent_age_group_45_54":1,"percent_age_group_55_plus":6},
[me:~]$ sed -n 's/.*track_name":"\(.*\)","artist_name.*/\1/p' work/tmp/example.txt | nl
     1  Thinking Out Loud

我省略了将该输出重定向到文件以作为示例显示。附加标准输出重定向,用于> file.txt写入文件。

也就是说,这取决于“track_name”位于“artist_name”之前,并且这些字符串都不位于该行的其他位置。这适用于 GNU Sed。

最终,这可能不是适合该工作的工具,因为您已经获得了显式格式化 (json) 文本,因此使用可以解析 json 的工具会更可靠。不同版本的 sed 可能支持不同的正则表达式扩展,因此结果可能因平台而异。

相关内容