Bash命令查看文件的特定行是否为空

标签 bash

我正在尝试通过添加一些错误捕获来修复 bash 脚本。我有一个文件 (list.txt),通常包含如下内容:

People found by location:  
person: john [texas]  
more info on john

有时该文件会损坏,并且只有第一行:

People found by location:

我正在尝试找到一种方法来检查该文件以查看第 2 行是否存在任何数据,并且我想将其包含在我的 bash 脚本中。这可能吗?

最佳答案

简单干净:

if test $(sed -n 2p < /path/to/file); then
    # line 2 exists and it is not blank
else
    # otherwise...
fi

使用 sed 我们只提取第二行。仅当文件中存在第二个非空行时,test 表达式的计算结果才为真。

关于Bash命令查看文件的特定行是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18492917/

相关文章:

linux - 用于测试文件是否包含多个字符串的 Bash 脚本,否则添加缺少的字符串?

bash - bash或powershell中的>>模式是什么?

linux - awk 只在 while 循环内打印第一行,除非回显,理论解释

php - 来自 BASH 的 Tcpdump

bash - 如何检查 gcc 是否失败、返回警告或在 Bash 中成功?

bash - 使用 OpenSSL 生成质数

arrays - Bash shell 脚本 : How to replace characters at specific byte offsets

bash - 追加 bash 参数并转发给其他脚本

bash - 在 bash 中将十六进制八位字节数组转换为字符串变量

bash - 意外的 EOF?