unix 如果文件的第一行为空,则删除它

iyzzxitl  于 2022-12-03  发布在  Unix
关注(0)|答案(5)|浏览(186)

如果一个文本文件的第一行是空的,我如何删除它,例如使用sed或其他标准UNIX工具。我尝试了以下命令:

sed '/^$/d' < somefile

但是这将删除第一个空行,而不是文件的第一行,如果它是空的,我可以给予sed一些关于行号的条件吗?
根据Levon的回答,我基于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
pokxtpni

pokxtpni1#

sed中最简单的事情是:

sed '1{/^$/d}'

请注意,这不会删除包含所有空格的行,而只会删除只包含一个换行符的行。要删除空格:

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

并消除所有空白:

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

请注意,某些版本的sed需要在块中使用终止符,因此您可能需要添加分号。例如sed '1{/^$/d;}'

35g0bw71

35g0bw712#

使用sed,尝试以下操作:

sed -e '2,$b' -e '/^$/d' < somefile

或进行适当的更改:

sed -i~ -e '2,$b' -e '/^$/d' somefile
0qx6xfy6

0qx6xfy63#

如果您不必就地执行此操作,则可以使用awk并将输出重定向到其他文件。

awk '{if (NR==1 && NF==0) next};1' somefile

这将打印文件的内容,除非它是第一行(NR == 1)并且不包含任何数据(NF == 0)。
NR当前行号,NF给定行上由空格/制表符分隔的字段数
例如:

$ cat -n data.txt
     1  
     2  this is some text
     3  and here
     4  too
     5  
     6  blank above
     7  the end

$ awk '{if (NR==1 && NF==0) next};1' data.txt | cat -n
     1  this is some text
     2  and here
     3  too
     4  
     5  blank above
     6  the end

cat -n data2.txt
     1  this is some text
     2  and here
     3  too
     4  
     5  blank above
     6  the end

$ awk '{if (NR==1 && NF==0) next};1' data2.txt | cat -n
     1  this is some text
     2  and here
     3  too
     4  
     5  blank above
     6  the end
  • 更新 *:

sed解决方案也适用于就地更换:

sed -i.bak '1{/^$/d}'  somefile

原始文件将以.bak扩展名保存

cngwdvgl

cngwdvgl4#

如果实际目录下所有文件的第一行为空,则删除第一行:
find -type f | xargs sed -i -e '2,$b' -e '/^$/d'

mec1mxoz

mec1mxoz5#

这可能对您有用:

sed '1!b;/^$/d' file

相关问题