0

我有一个 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

我怎样才能做到这一点?

谢谢

4

3 回答 3

4

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

替换.[^-]

$ 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
于 2013-10-25T08:10:55.377 回答
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 列返回到行尾
于 2013-10-25T16:44:58.960 回答
0

使用awkfalsetru 示例中的正则表达式

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(alo copy regex from falsetru)
这使用反向引用

awk '{print gensub(/[^-]* - [^-]* - ([^-]*)/,"\\1","g")}' file
于 2013-10-25T08:40:34.757 回答