簡體   English   中英

理解sed表達式's/^\\.\\///g'

[英]Understanding sed expression 's/^\.\///g'

我正在學習 Bash 編程,我找到了這個例子,但我不明白它是什么意思:

filtered_files=`echo "$files" | sed -e 's/^\.\///g'`

特別是在“-e”之后傳遞給sed的參數。

這是一個糟糕的例子; 你不應該遵循它。


首先,了解手頭的 sed 表達式。

s/pattern/replacement/flags是一個sed命令,在man sed中有詳細描述。 在這種情況下, pattern是一個正則表達式; replacement是該模式被何時/何地找到; flags描述了有關如何進行替換的詳細信息。

在這種情況下, s/^\\.\\///g分解如下:

  • s是正在運行的sed命令。
  • /是用於分隔此命令部分的符號。 (任何字符都可以用作符文,選擇使用/表示這個表達的人是慈善的,沒有考慮他們在做什么很努力)。
  • ^\\.\\/是要替換的模式。 ^表示這僅在開頭替換任何內容; \\. 僅匹配一個句點,而. (這是匹配任何字符的正則表達式); 並且\\/只匹配一個/ (vs / ,這將繼續到這個 sed 命令的下一部分,作為選定的符號)。
  • 下一部分是一個空字符串,這就是為什么以下兩個 sigil 之間沒有內容的原因。
  • flags部分中的g表示每行可以發生多次替換。 結合^ ,這沒有意義,因為每行只能有一個行首; 進一步證明寫你的例子的人並沒有想太多。

使用相同的數據結構,做得更好:

在處理任意文件名時,以下所有內容都是錯誤的,因為在標量變量中存儲任意文件名通常是錯誤的。

  1. 仍在使用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'`)
  2. 用內置的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM