首页 > shell脚本删除文本最后空行的问题

shell脚本删除文本最后空行的问题

有一个文本a.txt,内容为

#####
jhasdfj
[这里有个空行]
asdfjalskdf
#
#
#
#
#

我想将最后的5行的#全部变为空行(不删除行),使用下面的脚本

#!/bin/sh  
a=`cat a.txt | sed 's/^#$//g'`  
a_length=`echo "$a" | awk 'END {print NR}'`  
echo "$a"  
echo $a_length

打印结果为

#####
jhasdfj
[这里有个空行]
asdfjalskdf
4

也就是说脚本将最后的空行给删除了,但中间的空行不会删除,这是为什么,如何不让它删除最后的空行?

另外补充一点,上面的命令在命令行下完全没有问题的,但在shell脚本里面就有问题


这应该是shell的标准造成的。

The shell shall expand the command substitution by executing command in a subshell environment (see Shell Execution Environment) and replacing the command substitution (the text of command plus the enclosing "$()" or backquotes) with the standard output of the command, removing sequences of one or more s at the end of the substitution.

至于为什么shell要这样设计,我只能说是"历史原因"。
使用其它的脚本语言应该可以避免这个问题。


试一下换成bash?

#!/bin/bash
【热门文章】
【热门文章】