Sed

獲取兩個字元串之間的字元串

  • November 14, 2018

我需要從這個字元串中獲取內部文本[%L10n.msg('foo')%][%L10n.msg('所以')%]在這個例子中我應該得到foo.

我發現了很多例子,但沒有一個有效,我嘗試了這樣的事情:

echo "[%L10n.msg('foo')%]" | sed -n -e '/[%L10n.msg(\'/,/\')%]/p'

但我得到錯誤

bash:意外標記 `)’ 附近的語法錯誤

更新: 想像一下我的字元串可以在這個字元串中:

Some ' very [%% ]long ' text [%L10n.msg('foo')%] with lot of [%characters%]

測試文件:

Some ' very [%% ]long ' text [%L10n.msg('foo')%] with lot of [%characters%]
fefe
         <a class="w3-bar-item w3-button" href='/html/html_examples.asp'>HTML Examples</a>

         <a class="w3-bar-item w3-button" href='/html/html_exercises.asp'>HTML Exercises</a>

fefrheerghirlg wgwa g [%L10n.msg('foo')%]


<>"

怎麼樣

$ echo "[%L10n.msg('foo')%]" | sed "s/\[%L10n.msg('//; s/')%]//"
foo

或者,使用您的新輸入樣本,

echo "Some ' very [%% ]long ' text [%L10n.msg('foo')%] with lot of [%characters%]" | sed "s/^.*\[%L10n.msg('//; s/')%].*$//"
foo

或者,第二次更改輸入(現在讀取測試文件),嘗試

sed -n "/^.*\[%L10n.msg('/ {s///; s/')%].*$//;p}" file
foo
foo

引用自:https://unix.stackexchange.com/questions/481761