【问题标题】:Remove an empty line at the end of a file (bash)删除文件末尾的空行 (bash)
【发布时间】:2017-08-09 05:57:32
【问题描述】:

如何删除文件末尾的空行?我尝试了sed 的多种组合,这是我目前的尝试。不使用awk可以去掉最后的空行吗?

printf "" > "temp.txt" #erases any current values in temp.txt
for num in "${myarr[@]}" #the value from the array was taken from a file with an empty line at the end as well
do
    echo $num >> "temp.txt" #writes new values in new line
done
sed '/^$/d' "temp.txt"

它与建议的副本的不同之处在于我正在使用

for var in "${@:3}"
do
    filename=${var}".txt"
    cut -d ',' -f "$var" mycsv.csv > "$filename"
done 

写入文件,因此我无法像在 while 循环中那样轻松控制写入文件的内容

【问题讨论】:

    标签: bash file sed terminal line


    【解决方案1】:

    只需添加$作为匹配最后一行的地址:

    sed '${/^[[:space:]]*$/d;}' temp.txt
    

    编辑:

    [[:space:]]* 匹配包含空格或制表符的行。

    要就地编辑文件,请添加-i 标志:

    sed -i.bak '${/^[[:space:]]*$/d;}' temp.txt
    

    原始文件将以.bak 扩展名保存在这里。

    您还可以将输出重定向到新文件:

    sed '${/^[[:space:]]*$/d;}' temp.txt > newtemp.txt
    

    【讨论】:

    • 当我将正则表达式用单引号括起来时出现sed: 1: "${/^$/d}": extra characters at the end of d command 错误,当我将正则表达式用双引号括起来时出现sed: 1: "${/^$/d}": extra characters at the end of d command 错误
    • 试试:sed '${/^$/d;}' file
    • 感谢您的回复!代码运行了,但是文件末尾还有一个空行
    • 我不确定这是否相关,但我正在将此代码作为脚本运行
    • 因为 sed 的正常输出是到stdout(你的终端)。查看我的更新以在适当的位置编辑文件。