bash:如何正确地将sed用于带空格和引号的变量?

时间:2018-07-26 14:59:22

标签: bash variables sed escaping

我对此感到非常困惑,并且它弄乱了我的代码: 我正在寻找一个在一行中包含空格的模式,我想在该模式之后打印单词。 虽然我可以在line变量中使用引号转引号(使用\“),但是在我的实际数据中却不能这样做(直接从给出格式的文件中读取该行...)

我看到了我不理解的行为:

 lineone='#include "COMPLEX_Other_chain_X.itp"'
 linetwo='Other_chain_X       2'
 pattern='Other_chain_X      '
 #pattern='Other_chain_X\ \ \ \ \ \ ' #alternative pattern, same issues

问题1:尽管该行中不存在该模式,但sed还是打印了sth(代表$ lineone)

 #this prints the entire value of $lineone, but should empty...
 echo "$lineone" |sed -e 's/.*Other_chain_X     //; s/}.*//' 
 #this works
 echo "$linetwo" |sed -e 's/.*Other_chain_X     //; s/}.*//' 


 #this give the output I want - because there are no spaces in the pattern I am looking for ?
 echo "$lineone" |sed -e 's/.*Other_chain_X//; s/}.*//' 
 echo "$linetwo" |sed -e 's/.*Other_chain_X//; s/}.*//' 

问题2:同样,即使模式不匹配(与问题1相同,但不使用变量lineone和linetwo),仍会打印sth。

 #why is the whole line printed here?
 echo '#include "COMPLEX_Other_chain_X.itp"' |sed -e 's/.*Other_chain_X     //; s/}.*//' 
 #my guess is that the syntax of the pattern with the spaces is wrong?

 echo "Other_chain_X       2" |sed -e 's/.*Other_chain_X     //; s/}.*//' #prints what I want

 echo "#include "COMPLEX_Other_chain_X.itp"" |sed -e "s/.*$pattern//; s/}.*//" #why is the whole line printed here?
 #my guess is that the syntax of the pattern with the spaces is not properly put into the variable?
 echo "Other_chain_X       2" |sed -e "s/.*$pattern//; s/}.*//" #prints what I want

 #why is the whole line printed here?
 echo "$lineone" |sed -e "s/.*$pattern//; s/}.*//" 
 echo "$linetwo" |sed -e "s/.*$pattern//; s/}.*//" #works fine

我意识到,当人们不得不逃脱空格或引号时,这与其他问题类似-尽管那里的解释都没有帮助我。问题似乎在于如何将字符串保存在变量中。 有人对此行为有解释吗?

这是行得通的,但我不明白为什么...

 echo "$linetwo" |sed -e "s/.*$pattern//; s/}.*//"

问题1和问题2:无论是否使用模式MISMATCH(lineone),sed都可以打印,无论使用变量还是字符串

0 个答案:

没有答案