字串代換 's'
 
   
's'字串代換,與 ex 中的代換功能差不多,格式如下:
  s/<pattern>/<replacement>/<flags>
在格式上的差別,就是 's'之前無任何 line number addressing ,那就會 作用在讀進來的每一行資料。而 ex 中若無任何 line number addressing 那所下的指令僅作用在游標所在那一行。
 
 
在 Shell script 中使用 Sed, 可以將shell 變數用於 sed script 中,很有彈性;例如
  sed "s/$var1/$var2/g"   #將所有的Old 改成 New 
 

sed 中的字串代換指令所用的分隔符號,可以使用任意字符。
 
   
習慣上最常用的符號是"/",如果要替換的字串中含有此符號就很不方便,例如下面的例子 要把字串 Dir1/Old 改成字串 Dir2/New:
  sed "s/Dir1\/Old/Dir2\/New/g"
 
   
如果改用其他符號,如下例,就很方便了:
  sed "s%Dir1/Old%Dir2/New%g"
 

Multiple Editing Scripts in Sed

cat file |
    sed "s/Old1/New1/g" |
    sed "s/Old2/New2/g" |
    while read LINE
    do
      some commands
    done
.
cat file |
    sed -e "s/Old1/New1/g" \
        -e "s/Old2/New2/g" |
    while read LINE
    do
      some commands
    done
.
the '&' in the replacement part means reusing 'pattern' here
the '/' separator, in fact could be ANY character.
<flags> are optional, and can be combined
  g replace all occurrences of RE by <replacement> (the default is to replace only the first)
  p write the pattern space only if the substitution was successful
  w <file> work as `p' flag, but the pattern space is written to <file>
  d where `d' is a digit, replace the d-th occurrence, if any, of RE by <replacement>

Regular Expression Web Page

Web Page Copyright: 亞洲大學資訊電機學院 連耀南 yaonanlien@asia.edu.tw  sub1.htm,  Fri Oct 27 21:34:57 CST 2023