首页 > 解决方案 > 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;

标签: linuxbashshellcat

解决方案


假如说

  1. 第一个零可以是文件名中的任何位置,
  2. 零后可能有多个同名文件,
  3. 您希望能够处理任何文件名,包括点文件和包含换行符的名称,以及
  4. 你已经安装了 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

解释:

  1. 打印所有 NUL 分隔的文件名并将它们读回以便能够对它们进行变量替换。
  2. 删除文件名中包含第一个零的所有内容并打印出来。
  3. 按文件名的其余部分排序,确保每个唯一后缀只打印一次。
  4. 处理以(现已排序)后缀结尾的每个文件。

推荐阅读