[英]Understanding sed expression 's/^\.\///g'
我正在學習 Bash 編程,我找到了這個例子,但我不明白它是什么意思:
filtered_files=`echo "$files" | sed -e 's/^\.\///g'`
特別是在“-e”之后傳遞給sed
的參數。
這是一個糟糕的例子; 你不應該遵循它。
s/pattern/replacement/flags
是一個sed
命令,在man sed
中有詳細描述。 在這種情況下, pattern
是一個正則表達式; replacement
是該模式被何時/何地找到; 和flags
描述了有關如何進行替換的詳細信息。
在這種情況下, s/^\\.\\///g
分解如下:
s
是正在運行的sed
命令。/
是用於分隔此命令部分的符號。 (任何字符都可以用作符文,選擇使用/
表示這個表達的人是慈善的,沒有考慮他們在做什么很努力)。^\\.\\/
是要替換的模式。 ^
表示這僅在開頭替換任何內容; \\.
僅匹配一個句點,而.
(這是匹配任何字符的正則表達式); 並且\\/
只匹配一個/
(vs /
,這將繼續到這個 sed 命令的下一部分,作為選定的符號)。flags
部分中的g
表示每行可以發生多次替換。 結合^
,這沒有意義,因為每行只能有一個行首; 進一步證明寫你的例子的人並沒有想太多。在處理任意文件名時,以下所有內容都是錯誤的,因為在標量變量中存儲任意文件名通常是錯誤的。
仍在使用sed
:
# Use printf instead of echo to avoid bugginess if your "files" string is "-n" or "-e" # Use "@" as your sigil to avoid needing to backslash-escape all the "\\"s filtered_files=$(printf '%s\\n' "$files" | sed -e 's@^[.]/@@g'`)
用內置的 bash 替換sed
:
# This is much faster than shelling out to any external tool filtered_files=${files//.\\//}
而不是跑步
files=$(find .)
...反而:
files=( )
while IFS= read -r -d '' filename; do
files+=( "$filename" )
done < <(find . -print0)
將文件存儲在數組中; 它看起來很復雜,但它更安全——即使文件名包含空格、引號、換行文字等,也能正常工作。
此外,這意味着您可以執行以下操作:
# Remove the leading ./ from each name; don't remove ./ at any other position in a name
filtered_files=( "${files[@]#./}" )
這意味着一個名為的文件
./foo/this directory name (which has spaces) ends with a period./bar
將正確地轉換為
foo/this directory name (which has spaces) ends with a period./bar
而不是
foo/this directory name (which has spaces) ends with a periodbar
...使用原始方法會發生這種情況。
man sed
。 特別是:
-e script, --expression=script
add the script to the commands to be executed
和:
s/regexp/replacement/
Attempt to match regexp against the pattern space. If success-
ful, replace that portion matched with replacement. The
replacement may contain the special character & to refer to that
portion of the pattern space which matched, and the special
escapes \1 through \9 to refer to the corresponding matching
sub-expressions in the regexp.
在這種情況下,它會用空字符串替換任何出現在行首的./
,即刪除它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.