linux - shell脚本删除文本最后空行的问题
PHPz
PHPz 2017-04-17 11:23:46
[Linux讨论组]

有一个文本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脚本里面就有问题

PHPz
PHPz

学习是最好的投资!

全部回复(2)
阿神

这应该是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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号