You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shell脚本中从文本提取指定格式的两个变量?

文本分割提取变量实现方案

针对「格式为艺术家名 - 歌曲名的文本,提取无末尾空格的艺术家名和歌曲名」的需求,以下是几种常用编程语言的实现方式:

Python 实现

利用字符串分割和末尾空格去除方法,确保只分割一次避免内容中含横杠的干扰:

text = "Barren Gates - Devil"
# 按' - '分割,仅分割1次
artist_part, songname = text.split(' - ', 1)
# 去除艺术家名末尾的空格(确保符合要求)
artist = artist_part.rstrip()

print(f"artist={artist}")
print(f"songname={songname}")

Bash 脚本实现

使用Shell的参数扩展完成截取,无需额外工具:

text="Barren Gates - Devil"
# 从右侧截取到第一个' - ',得到艺术家名
artist="${text% - *}"
# 从左侧截取掉第一个' - ',得到歌曲名
songname="${text#* - }"

echo "artist=$artist"
echo "songname=$songname"

JavaScript 实现

通过字符串分割和末尾空格修剪处理:

const text = "Barren Gates - Devil";
// 分割为两部分,限制仅分割1次
const [artistPart, songname] = text.split(' - ', 2);
// 去除艺术家名末尾空格
const artist = artistPart.trimEnd();

console.log(`artist=${artist}`);
console.log(`songname=${songname}`);

核心思路

  1. 以固定分隔符' - '(空格+横杠+空格)作为分割标识,避免误分割内容中单独出现的横杠;
  2. 限制仅分割1次,确保歌曲名中包含横杠时不会被拆分;
  3. 对艺术家名做末尾空格去除处理,严格符合变量结尾无空格的要求。

内容的提问来源于stack exchange,提问作者Esrarengiz Kahraman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 11:57:09