我在Perl中使用正則表達式確定,但不必在BASH中完成。BASH中的正則表達式?
我試圖谷歌的某種教程,但沒有看到任何真正的好,但與Perl的方式。
我所試圖實現的是剝離/home/devtestdocs/devtestdocs-repo/
了一個名爲$filename
變量和一個名爲$testdocsdirurl
希望另一個變量是有道理的替換它,如果任何人有這將是非常讚賞的任何良好的聯繫。
另一種可能的方式是,如果已經有人寫了一個函數來做bash中的查找和替換。
我在Perl中使用正則表達式確定,但不必在BASH中完成。BASH中的正則表達式?
我試圖谷歌的某種教程,但沒有看到任何真正的好,但與Perl的方式。
我所試圖實現的是剝離/home/devtestdocs/devtestdocs-repo/
了一個名爲$filename
變量和一個名爲$testdocsdirurl
希望另一個變量是有道理的替換它,如果任何人有這將是非常讚賞的任何良好的聯繫。
另一種可能的方式是,如果已經有人寫了一個函數來做bash中的查找和替換。
sed
是字符串操作在Unix中選擇的典型武器:
echo $filename | sed s/\\/home\\/devtestdocs\\/devtestdocs-repo\\//$testdocsdirurl/
此外,如跳建議,您可以使用@
語法,以避免逃逸路徑:
echo $filename | sed [email protected]/home/devtestdocs/devtestdocs-repo/@[email protected]
非常感謝你幫助一個例子 – martincarlin87
sed通常也理解s @ pattern @ string @,所以你不必在路徑中痛苦地逃避斜槓。 – hop
@hop:謝謝,不知道這個語法。 –
你可以在沒有正則表達式的情況下實現:
somepath="/foo/bar/baz"
newprefix="/alpha/beta/"
newpath="$newprefix${somepath##/foo/bar/}"
爲什麼你需要正則表達式嗎?
這些只是幾種可能性:
$ filename=/home/devtestdocs/devtestdocs-repo/foo.txt
$ echo ${filename/'/home/devtestdocs/devtestdocs-repo/'/'blah/'}
blah/foo.txt
$ basename $filename
foo.txt
$ realfilename=$(basename "$filename")
另請參閱:http://www.gnu.org/software/bash/manual/bashref。html#Shell-Parameter-Expansion –
謝謝,我只是認爲使用正則表達式將是繼續這一項的方式。 – martincarlin87
@ martincarlin87:一個好的經驗法則是:正則表達式應該是您應該解決任何問題的最快方式。 – hop
是,bash的支持正則表達式,如
$ [[ 'abc' =~ (.)(.)(.) ]]
$ echo ${BASH_REMATCH[1]}
a
$ echo ${BASH_REMATCH[2]}
b
但你可能更願意使用basename
實用
$ f='/some/path/file.ext'
$ echo "/new/path/$(basename $f)"
/new/path/file.ext
信息的極好來源是bash的手冊頁
使用bash
pattern=/home/devtestdocs/devtestdocs-repo/
testdocsdirurl=/tmp/
filename=/foo/bar/home/devtestdocs/devtestdocs-repo/filename
echo ${filename/$pattern/$testdocsdirurl} # => /foo/bar/tmp/filename
你正在尋找一個如何在PowerShell中使用正則表達式的例子?
是這裏有一個例子:
$input = "hello,123"
$pattern = ([regex]"[0-9]+")
$match = $pattern.match($input)
$ok = $input -match $pattern #return an boolean value if matched..
if($ok) {
$output = $match.groups[0].value
[console]::write($output)
} else {
//no match
}
在 'bash的經典的' 正則表達式的使用是危險的。 你可以用這個: http://www.robvanderwoude.com/findstr.php
他要求提供UNIX shell'bash'(Bourne Again SHell),而不是批處理文件或Window PowerShell。 – DarkDust
我在這裏看不到正則表達式的需要。你能解釋爲什麼你認爲你需要他們嗎? – hop