简体   繁体   中英

Sed script in bash script

I am trying to make a script which only gives me code outside braces. I made a bash script to which I can give the braces I like. Then I would like to use sed inside my bash script. My sed script does what it has to do, because when I use sed -f myscript on the command line, the output is right. But I now have problems to replace the braces I give to my bash script in the sed script. Here is my code:

#/bin/bash

if [[ $# != 2 ]]
then
    echo "Gebruik: verwijderhaakjes.sh <openend symbool> <sluitend symbool>"
    exit
fi
if [ "${#1}" != 1 -o "${#2}" != 1 ]
then
    echo "Fout: openend en sluitend symbool moeten uit één enkel karakter bestaan"
    exit
fi
var1=$1
var2=$2
sed "
$!{
    /^[a-zA-Z]/{
        H
        d
    }
    /^${var2}/{
        H
        d
    }
    /^[ ][ ]*/{
        d
    }
}
/^[${var2}a-zA-Z]/{
    H
}
x
s/${var1}\n//g
s/${var2}//g
p
"

As you can see, I already used double quotes and I used the variables in the sed script, so I don't know why I don't get any output.

for example:

testfile:

aaa {
  bbb
  ccc {
    ddd
    eee
  } fff {
    ggg
    hhh
  }
  iii
  jjj
} kkk {
  lll
  mmm
} nnn
ooo
ppp

When I use my sed script like this:

sed -f myscript.sed test.txt

the output is this:

aaa kkk nnn
ooo
ppp

which is right. However when I use my sed script in bash I don't get any ouput. What I want to get is:

cat test | bash bashscript.sh "{" "}"

aaa kkk nnn
ooo
ppp

or

cat test | tr '}' ']' | tr '{' '[' | bash bashscript.sh "[" "]"

aaa kkk nnn
ooo
ppp

Try this instead:

sed '
$!{
    /^[a-zA-Z]/{
        H
        d
    }
    /^'"${var2}"'/{
        H
        d
    }
    /^[ ][ ]*/{
        d
    }
}
/^['"${var2}"'a-zA-Z]/{
    H
}
x
s/'"${var1}"'\n//g
s/'"${var2}"'//g
p
'

If you use double-quotes around the entire sed expression, the shell will expand characters like $ , * etc. So you need to use single quotes around everything except the shell variables.

Another approach would be to escape the characters which are special to the shell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM