【问题标题】:How can I split a string into 3 Parts, even if the delimiter exists more than twice即使分隔符存在两次以上,如何将字符串拆分为 3 部分
【发布时间】:2013-10-25 08:09:35
【问题描述】:

我有一个 linux 接收器,想重命名录音。录音看起来像 20131018 2245 - Channel 1 - Name of the movie.ts

我只想获得“电影名称.ts”。我可以使用以下 sed- 命令轻松做到这一点:

echo 20131018 2245 - Channel 1 - Name of the movie.ts|sed 's!\(.*\) - \(.*\) - \(.*\)!\3!'

但是:如果电影名称也包含分隔符“ - ”,那么它将在分隔符处将其切断:

echo 20131018 2245 - Channel 1 - Name of another movie - Second part.ts|sed 's!\(.*\) - \(.*\) - \(.*\)!\3!'

将输出:

另一部电影的名称

而不是

另一部电影的名称 - 第二部分.ts

我怎样才能做到这一点?

感谢

【问题讨论】:

  • 如果您在正则表达式的开头添加^,则它不可能引用最后的 3,但最后一个会很贪心并占据其余部分。

标签: regex string shell sed split


【解决方案1】:

.* 尽可能匹配(贪心)。

. 替换为[^-]

$ filename='20131018 2245 - Channel 1 - Name of another movie - Second part.ts'
$ echo $filename | sed 's!\([^-]*\) - \([^-]*\) - \([^-]*\)!\3!'
Name of another movie - Second part.ts

没有捕获组:

$ echo $filename | sed 's![^-]* - [^-]* - !!'
Name of another movie - Second part.ts

【讨论】:

  • 这个sed 's!\([^-]*\) - \([^-]*\) - \([^-]*\)!\3!'可以缩写成sed 's![^-]* - [^-]* - \([^-]*\)!\1!',你不需要所有的引用。
  • 第二个例子非常简单,非常适合我能找到的所有例子!谢谢
【解决方案2】:

对于分割字符串,您可能更喜欢使用 'cut' 命令:

你要替换的字符串:

filename='20131018 2245 - Channel 1 - Name of another movie - Second part.ts'

要应用的命令:

echo $filename | cut -d\- -f3-
  • -d:定义分隔符
  • -f:定义要提取的列

例如:

  • -f3 : 返回第三列
  • -f3-5 : 返回第 3 到 5 列
  • -f1,3- :将第 1 列和第 3 列返回到行尾

【讨论】:

  • 您的答案似乎最适合原始问题,但我接受的答案更接近关于 sed 的问题......但是:谢谢
【解决方案3】:

使用 awk 和 falsetru 示例中的正则表达式

cat file
20131018 2245 - Channel 1 - Name of another movie - First part.ts
20131019 2245 - Channel 1 - Name of another movie - Second part.ts
20131022 1520 - Channel 3 - A good movie.ts


awk '{sub(/[^-]* - [^-]* - /,x)}1' file
Name of another movie - First part.ts
Name of another movie - Second part.ts
A good movie.ts

一个 gnu awk version(从 falsetru 复制正则表达式)
这使用反向引用

awk '{print gensub(/[^-]* - [^-]* - ([^-]*)/,"\\1","g")}' file

【讨论】:

    猜你喜欢
    • 2020-06-18
    • 2016-04-06
    • 2017-04-29
    • 2014-06-29
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多