linux - Sort files in directory and then printing the content
问题描述
I need to write a script to sort filenames by the character that comes after the first "0" in the name. All the file names contain at least one 0. Then the script should print the content of each file by that order.
I know i need to use sort and cat. But i can't figure out what sort. This is as far as I've got.
#!/bin/bash
dir=$(pwd)
for n in $dir `ls | sort -u ` ; do
cat $n
done;
解决方案
假如说
- 第一个零可以是文件名中的任何位置,
- 零后可能有多个同名文件,
- 您希望能够处理任何文件名,包括点文件和包含换行符的名称,以及
- 你已经安装了 GNU CoreUtils(普通发行版的标准),
你需要做一些像这样疯狂的事情(未经测试):
find . -mindepth 1 -maxdepth 1 -exec printf '%s\0' {} + | while IFS= read -r -d ''
do
printf '%s\0' "${REPLY#*0}"
done | sort --unique --zero-terminated | while IFS= read -r -d ''
do
for file in ./*"$REPLY"
do
[…]
done
done
解释:
- 打印所有 NUL 分隔的文件名并将它们读回以便能够对它们进行变量替换。
- 删除文件名中包含第一个零的所有内容并打印出来。
- 按文件名的其余部分排序,确保每个唯一后缀只打印一次。
- 处理以(现已排序)后缀结尾的每个文件。
推荐阅读
- visual-studio-code - 使用在 Windows 10 中运行的 VSCode 调试在 WSL 中运行的 Java
- php - 只显示不在其他表 laravel 中的项目
- html - 响应式网格宽度不同高度列
- python - 使用带有 tensorflow 的鼠标事件函数进行对象检测时出现列表索引超出范围错误
- antlr4 - Antlr4 Testrig 运行,但没有输出
- jquery - 如何对具有不同属性名称的所有值求和
- c - 如何在 Visual Studio 中包含头文件和源文件文件夹
- macos - 为什么我需要将 hadoop 作为 sudo 执行?
- h2o - 将模型导入 R,该模型是在较新版本的 H2O 中创建的
- javascript - 具有自定义 xml 或 json 结构的 JsTree