如果文件的第一行为空,则删除它 [英] Delete first line of file if it's empty

查看:39
本文介绍了如果文件的第一行为空,则删除它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文本文件为空,我如何删除它的第一行(!),例如使用sed 或其他标准 UNIX 工具.我试过这个命令:

How can I delete the first (!) line of a text file if it's empty, using e.g. sed or other standard UNIX tools. I tried this command:

sed '/^$/d' < somefile

但是这将删除第一个空行,而不是文件的第一行,如果它是空的.我可以给 sed 一些关于行号的条件吗?

But this will delete the first empty line, not the first line of the file, if it's empty. Can I give sed some condition, concerning the line number?

根据 Levon 的回答,我基于 awk 构建了这个小脚本:

With Levon's answer I built this small script based on awk:

#!/bin/bash

for FILE in $(find some_directory -name "*.csv")
do
    echo Processing ${FILE}

    awk '{if (NR==1 && NF==0) next};1' < ${FILE} > ${FILE}.killfirstline
    mv ${FILE}.killfirstline ${FILE}

done

推荐答案

sed 中最简单的事情是:

The simplest thing in sed is:

sed '1{/^$/d}'

请注意,这不会删除包含所有空格的行,而只会删除仅包含一个换行符的行.摆脱空白:

Note that this does not delete a line that contains all blanks, but only a line that contains nothing but a single newline. To get rid of blanks:

sed '1{/^ *$/d}'

并消除所有空格:

sed '1{/^[[:space:]]*$/d}'

这篇关于如果文件的第一行为空,则删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆