【问题标题】:Find regex text and replace with text that contains brackets and quotes using sed使用 sed 查找正则表达式文本并替换为包含括号和引号的文本
【发布时间】:2020-08-09 12:38:52
【问题描述】:

我正在尝试使用一行代码来查找并用一长串前缀和后缀代码替换文本。

原始文件:

1. 'text that will go here'
2. 'more text that will be here'
3. 'even more text'

替换后:

youtube-dl -f 'bestvideo[height<=360]+bestaudio/best[height<=360]' --postprocessor-args "-ss 0:0:55 -to 0:1:05" "ytsearch1:text that will go here" -o "text that will go here";
youtube-dl -f 'bestvideo[height<=360]+bestaudio/best[height<=360]' --postprocessor-args "-ss 0:0:55 -to 0:1:05" "ytsearch1:more text that will be here" -o "more text that will be here";
youtube-dl -f 'bestvideo[height<=360]+bestaudio/best[height<=360]' --postprocessor-args "-ss 0:0:55 -to 0:1:05" "ytsearch1:even more text" -o "even more text";

我有以下匹配 # 的正则表达式。 ' 并替换它,但是当我尝试用代码替换它时,sed 不会接受它并发出错误。这是我试图使用的:

sed -e "s/^.*\d. '/youtube-dl -f 'bestvideo[height<=360]+bestaudio/best[height<=360]' --postprocessor-args "-ss 0:0:55 -to 0:1:05" "ytsearch1:/g" original.txt > new.txt

我知道为什么它不起作用,因为替换为其中有一堆斜杠和引号,但我不知道如何让 sed 接受这些字符来替换,所以它不会破坏整个命令。

【问题讨论】:

    标签: sed


    【解决方案1】:

    使用扩展正则表达式:

    sed -E "s|^.*'(.*)'.*|youtube-dl -f 'bestvideo[height<=360]+bestaudio/best[height<=360]' --postprocessor-args \"-ss 0:0:55 -to 0:1:05\" \"ytsearch1:\1\" -o \"\1\";|" file
    

    或使用正则表达式:

    sed "s|^.*'\(.*\)'.*|youtube-dl -f 'bestvideo[height<=360]+bestaudio/best[height<=360]' --postprocessor-args \"-ss 0:0:55 -to 0:1:05\" \"ytsearch1:\1\" -o \"\1\";|" file
    

    见:Escaping forward slashes in sed command

    【讨论】:

    • 它几乎可以工作,唯一的问题是它与我的正则表达式不完全匹配。它正在执行 ^.* 而不是 ^.*\d。 ' 并且缺少 \d 部分,看起来也跟在它后面。
    • @user2406786 但这给出了问题中提到的输出..有时有不同的方法可以解决相同的问题..还要注意sed不支持\d,你需要使用[0-9]
    猜你喜欢
    • 2014-01-18
    • 2016-07-21
    • 1970-01-01
    • 2020-07-12
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多