2014-03-12 212 views
0

我想刪除包含字符串的行通過參數,但我無法讓它正常工作。我在OSX 10.9上。刪除包含字符串的行

sed -i '' '/$2/d' /etc/hosts

應該不是工作?它只是保持文件。沒有什麼變化。我的命令是sudo hosts remove junior.dev

這裏是我的shell腳本:

#!/bin/sh 

let $# || { echo No arguments supplied. Example: hosts add 192.168.2.2 mysite.dev; exit 1; } 

if [ $1 = "add" ]; then 
    if [ -z "$2" ] || [ -z "$3" ]; then 
     echo "You must supply an IP address and a host name." 
     exit 1; 
    else 
     echo "$2\t$3" >> /etc/hosts 
     echo "Done." 
    fi 
fi 

if [ $1 = "remove" ]; then 
    if [ -z "$2" ]; then 
     echo "You must supply a host name." 
     exit 1; 
    else 
     sed -i '' '/$2/d' /etc/hosts 
     echo "Done." 
    fi 
fi 

回答

2

使用雙引號"

$ echo "$foo" 
> bar 
$ echo '$foo' 
> $foo 

當使用雙引號"使用單引號'時,變量擴大,他們沒有擴大。