2016-12-01 86 views
0

我已经编写了一个shell脚本,用于替换属性文件中的某些属性。但脚本运行后,在替换之前文件末尾没有空行。使用echo和sed后缺少空行

file=my_file.properties 
file_content=$(cat $file | sed "[email protected]=.*@[email protected]") #making a=b 
file_content=$(echo "${file_content}" | sed "[email protected]=.*@[email protected]") #making x=y 
echo "${file_content}" > $file 

my_file.properties是一样的东西

1)a=v 
2)b=c 
3)x=b 
4) 

注有空白行中end.These数字只是用于参考显示空行

+0

在问题中添加文件'my_file.properties'的一些示例内容。 – GurV

回答

1

the Bash manual$(…)Command Substitution(重点煤矿):

Bash执行通过在子环境中执行命令进行扩展,并用命令的标准输出替换命令替换,删除任何尾随的换行符

因此,而不是捕捉命令的输出到一个变量,你应该捕捉它们到一个临时文件:

sed "[email protected]=.*@[email protected]" $file | sed "[email protected]=.*@[email protected]" > tmp.tmp 
mv tmp.tmp $file 

或者,如果你使用的是GNU sed的,你可以做到这一点的一条线:

sed -i -e "[email protected]=.*@[email protected]" -e "[email protected]=.*@[email protected]" $file 

-i意味着编辑到位的文件,因此不需要临时文件。

+0

此外,几乎没有理由在脚本中实际使用'cat'。 –

+0

为什么,你如何得到文件内容 –

+0

'cat filename | sed ...'涉及两个进程,'sed ... filename'做同样的事情,只需要一个。 –