多串命令输出只保存一串

Save only one string of multi-string command output

我有一个 bash 命令来查找子目录中的最大文件。我想将输出保存到一个变量,以便与其他命令一起使用。

bigile=$(find /path/to/directory -type f -exec du -Sh {} + | sort -rh | head -n 1)

不幸的是,这节省了文件大小和文件路径。

echo $file
216K /path/to/directory/bigfile

如果我将变量传递给将文件作为输入的命令,我会看到一个错误:

wc -lm $file
wc: cannot access '216K': No such file or directory
6333 217649 /home/path/to/directory/bigfile

显然,我得到了我需要的输出,但我不想要错误消息。如何只保存 find 命令输出的第一个字符串?

谢谢!!!

能否请您尝试关注,如果对您有帮助,请告诉我。

bigile=$(find /path/to/directory -type f -exec du -Sh {} + | sort -rh | awk 'FNR==1{print }')

说明: 只需在 sort 命令后添加 awk 并且 FNR==1 条件将确保仅选择第一行然后也打印该行的第二个字段。

在 bash(sed、awk、substring removal 中有很多方法可以做到这一点。试试这个:

bigile="$(find /path/to/directory -type f -exec du -Sh {} + | sort -rh | head -n1 | cut -f2-)"

在您的命令中添加了 cut -f2- 和引号 "。也适用于包含空格或制表符的文件名。

您还可以从扩展中删除前导文件大小:

echo "${file#* }"