2016-08-24 73 views
0

我写bash脚本一个反斜杠和我有一个变量SED去除变量

TYPE="type=\$(echo \"\$type\" | sed 's|/|\\/|g')" 

,我想插入到一个文本文件

试图插入到第15行使用sed的

sed -i "15i$TYPE" filename 

出应插入到文件中的行应是

type=$(echo "$type" | sed 's|/|\\/|g') 

但我得到:

type=$(echo "$type" | sed 's|/|\/|g') 

有一个反斜杠丢失,我怎么能获得与2个反斜杠所需的输出。

+0

谢谢,但我得到了和我以前一样的确切线 –

回答

0

你得到一个反斜杠一对双引号中 - 只需使用2对

TYPE="type=\$(echo \"\$type\" | sed 's|/|\\\\/|g')" 
1

使用这里-DOC,以避免不必要的转义:

read -r TYPE <<-'EOF' 
type=$(echo "$type" | sed 's|/|\\\\/|g') 
EOF 

记住,你需要输入\\为每个\

然后用它作为:

sed -i "15i$TYPE" filename 
+0

@Max_il:这是否工作? – anubhava

0

变量TYPE没有得到双重反弹:

$ TYPE="type=\$(echo \"\$type\" | sed 's|/|\\/|g')" 
$ echo "$TYPE" 
type=$(echo "$type" | sed 's|/|\/|g') 

有几种方法可以进去TYPE值包含正确的字符串:

  • 转换每个所需的\一逃脱\\之一:

    $ TYPE="type=\$(echo \"\$type\" | sed 's|/|\\\\/|g')"; echo "$TYPE" 
    type=$(echo "$type" | sed 's|/|\\/|g') 
    
  • 使用单引号作为外部容器:

    $ TYPE='type=$(echo "$type" | sed '\''s|/|\\/|g'\'')'; echo "$TYPE" 
    type=$(echo "$type" | sed 's|/|\\/|g') 
    
  • 用printf作为帮助:

    $ printf -v TYPE '%s' 'type=$(echo "$type" | sed '\''s|/|\\/|g'\'')'; echo "$TYPE" 
    type=$(echo "$type" | sed 's|/|\\/|g') 
    
  • 使用C字符串风格:

    $ TYPE=$'type=$(echo "$type" | sed \047s|/|\\\\/|g\047';echo "$TYPE" 
    type=$(echo "$type" | sed 's|/|\\/|g' 
    
  • 或者使用读取的-r选项,以避免转换\\

    $ read -r TYPE <<\EOF 
    > type=$(echo "$type" | sed 's|/|\\/|g' 
    > EOF 
    
    $ echo "$TYPE" 
    type=$(echo "$type" | sed 's|/|\\/|g' 
    
0

要使用bash更改变/\就是:

$ type='a/b/c' 
$ type="${type//\//\\}" 
$ echo "$type" 
a\b\c 

即不需要SED。如果你想要把一条线,这是否像一个文件:

$ cat file 
a 
b 
c 
d 

那么这是任一:

$ awk 'BEGIN{var=ARGV[1]; ARGV[1]=""} NR==3{print var}1' 'type="${type//\//\\}"' file 
a 
b 
type="${type//\//\\}" 
c 
d 

$ var='type="${type//\//\\}"' awk 'NR==3{print ENVIRON["var"]}1' file 
a 
b 
type="${type//\//\\}" 
c 
d 

更改3以上15或任何你喜欢。