bash变量不适用于脚本中的ex

时间:2013-12-15 23:47:36

标签: bash vi ex

我的bash脚本有点问题。

 #!/bin/bash
 ex xxx.html << "HERE"
 1,$s/\(foo\)/$1\1/
 wq
 HERE

这只是我脚本的一小部分。当我运行它时,这就是输出。

$1foo

任何方法来解决这个问题,所以$ 1将是给脚本的参数吗?

谢谢!

3 个答案:

答案 0 :(得分:2)

尝试将"HERE"替换为HERE(未引用)。此外,1,$s变为1,\$s

Here Documents
   This type of redirection instructs the shell to  read  input  from  the
   current source until a line containing only delimiter (with no trailing
   blanks) is seen.  All of the lines read up to that point are then  used
   as the standard input for a command.

   The format of here-documents is:

          <<[-]word
                  here-document
          delimiter

   No  parameter expansion, command substitution, arithmetic expansion, or
   pathname expansion is performed on word.  If any characters in word are
   quoted,  the  delimiter is the result of quote removal on word, and the
   lines in the here-document are not expanded.  If word is unquoted,  all
   lines  of  the here-document are subjected to parameter expansion, com-
   mand substitution, and arithmetic expansion.  In the latter  case,  the
   character  sequence  \<newline> is ignored, and \ must be used to quote
   the characters \, $, and `.

   If the redirection operator is <<-, then all leading tab characters are
   stripped  from  input  lines  and  the line containing delimiter.  This
   allows here-documents within shell scripts to be indented in a  natural
   fashion.

Bash手册。

答案 1 :(得分:2)

使用"HERE"(不带引号)重新HERE,并使用1,$1,\$

重新%

您可以按如下方式编写脚本:

#!/bin/bash
ex xxx.html <<-HERE
%s/foo/$1&/
x
HERE

虽然您也可以构建一个较小的脚本:

#!/bin/bash
sed -i "s/foo/$1&/g" xxx.html

答案 2 :(得分:0)

试试这个。

#!/bin/bash
(echo '1,$s/\(foo\)/'"$1"'\1/'; echo 'wq') | ex xxx.html

单引号中的1,$s/\(foo\)/,双引号中的$1旁边(因此shell会替换参数),在单引号中与\1/相邻。