删除文件末尾的空行(bash)

时间:2017-03-17 15:32:37

标签: bash file sed terminal line

如何删除文件末尾的空行?我尝试了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循环中那样轻松控制写入文件的内容

1 个答案:

答案 0 :(得分:1)

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

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

修改

[[:space:]]*匹配该行,如果它包含空格或制表符。

要编辑文件,请添加-i标记:

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

原始文件将以.bak扩展名保存在此处。

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

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