cat一个文件并在一行中检查它

问题描述 投票:0回答:2

我的linux命令是

cat /etc/myfile.txt > newfile.txt

我的问题是如何检查文件/etc/myfile.txt是否为空并保存

一个命令行中的文件

linux bash shell sh
2个回答
3
投票

你可以使用bash中的条件表达式来检查文件是否存在(-f标志),而不是用-s标志清空。

你也可以使用cp创建一个新的文件副本而不是cat-ing它。

if [[ -f /etc/myfile.txt && -s /etc/myfile.txt ]]; then 
    cp /etc/myfile.txt  newfile.txt
fi

不知道为什么你会打扰使用单行而不是正确的可读示例。无论如何,你可以使用上面的逻辑

[[ -f /etc/myfile.txt && -s /etc/myfile.txt ]] && cp /etc/myfile.txt newfile.txt

3
投票
    [ -s "/etc/myfile.txt" ] && cat /etc/myfile.txt > newfile.txt

你没有cat文件,而是使用cp

这里,-s选项检查文件的大小是否为非零。来自Linux盒子上的man test

        -s FILE
          FILE exists and has a size greater than zero

编辑:如果/etc/myfile.txt是一个常规文件,上述解决方案就足够了。如果要在检查non-zero大小之前检查它是否是常规文件,则需要-f标志

 [[ -f "/etc/myfile.txt" && -s "/etc/myfile.txt" ]] && cp /etc/myfile.txt newfile.txt
© www.soinside.com 2019 - 2024. All rights reserved.