Как проверить, присутствует ли файл, начинающийся с определенного префикса, в каталоге в сценарии оболочки [закрыто]

Это решение с использованием Awk:

#!/usr/bin/awk -f

NR == 1 {
    # Get the headers on the first line.
    # Will be done for both files, but we don't mind.
    head[1] = $1;
    head[2] = $2;
}

NR == 3 {
    # For the third line, go though the data in both columns...
    for (i = 1; i <= 2; ++i) {
        # If there's something in col[], then this is the second file.
        if (col[i]) {
            # This is the second file.
            # Test the value of the column against what was in the first file.
            if (col[i] == $i) {
                printf("%s is matching. ", head[i]);
            } else {
                printf("%s is not matching. ", head[i]);
                # Flag that we need to print extra info later.
                check = 1;
            }
        } else {
            # This is the first file.
            # Remember the data in the two columns.
            col[1] = $1;
            col[2] = $2;

            # Reset the record (line) counter.
            NR = 0;

            # Skip to the second file.
            nextfile;
        }
    }

    if (check) {
        printf("Please check.");
    }

    printf("\n");
}

Тестирование:

$ ./script.awk file1 file2
NAME is not matching. OPEN_MODE is matching. Please check.
1
27.07.2016, 17:45
2 ответа

Вот еще один способ сделать это:

-sh-4.1$ dir=$(pwd)  ; filename="ant" 

if (( $(shopt -s nullglob; set -- ${dir}/${filename}*;  echo $#) > 0 ));  then rm
${dir}/${filename}* ; fi    

shopt -s nullglob : гарантирует, что уведомление будет возвращено, если каталог пуст.

set - $ {dir} / $ {filename} *: устанавливает позиционный параметр.

$ # : возвращает количество позиционных параметров. в качестве условия для исключения rm

как одной линейной:

1$ dir=$(pwd) ; filename="ant" ;  if (( $(shopt -s nullglob; set -- ${dir}/${filename}*;  echo $#) > 0 )); then rm     ${dir}/${filename}* ; fi     
1
27.01.2020, 23:19

Один портативный способ удалить такой файл, если существует только один:

set -- "${FILE_PATH}/${FILE_NAME}"*
[ $# -eq 1 -a -e "$1" ] && rm -- "$1"

Мне кажется, что если вас не волнует, сколько таких "ant" файлов существует заранее, но вы хотите, чтобы они (все) исчезли, когда вы закончите, просто:

rm -f "${FILE_PATH}/${FILE_NAME}"*

-- таким образом, если таких файлов не было, rm (принудительно-тихий) ничего не сделает, но если такие файлы были (любые -- 1 или более!), rm удалит их.

3
27.01.2020, 23:19

Теги

Похожие вопросы