如何在bash中替换字符串数组的所有子字符串?

问题描述

我试图列出子目录中没有路径的所有文件,我只想要文件名和扩展名,但是 Bash 替换不适用于数组中的所有路径,它只适用于第一个元素.

代码

#!/usr/bin/bash

NAME="$(pwd | grep -o '[^/]*$')"

# ls src -R
PATH="$(ls src/*.{cpp,hpp} 2> /dev/null)"
if [ 0 -eq "${#PATH[@]}" ]; then
    echo "The project has no source code file yet."
    exit 0
fi

EMPTY=''
for FILE in "${PATH[@]}"; do
    echo "${FILE/src\//$EMPTY}"
done

目录树:

FileReader
├── bin
├── make.sh
├── obj
└── src
    ├── FileReader.cpp
    ├── FileReader.hpp
    └── main.cpp

预期:

$ bash make.sh

FileReader.cpp
FileReader.hpp
main.cpp

输出

$ bash make.sh

FileReader.cpp
src/FileReader.hpp
src/main.cpp

解决方法

parsing ls is bad 开始,我会执行以下操作:

#!/usr/bin/env bash

# If no matching files,globs expand to an empty string instead of the pattern
shopt -s nullglob
declare -i count=0
for file in src/*.[ch]pp; do
    count+=1
    printf "%s\n" "$(basename "$file")"
done

[[ $count -eq 0 ]] && echo "The project has no source code file yet."

避免文件名中出现有趣字符的问题。 basename(1) 从文件名(以及可选的给定扩展名)中删除前导目录组件。

您还可以使用 files=( src/*.[ch]pp ) 安全地获取数组中的文件,并使用更接近您原始方法的方法。我会绝对避免调用变量 PATH,尽管这与内置变量相冲突。

基于数组的版本(该版本使用 ${variable#pattern} 参数扩展语法,从变量值的开头去除模式的匹配文本):

#!/usr/bin/env bash

shopt -s nullglob
files=( src/*.[ch]pp )

if [[ "${#files[@]}" -eq 0 ]]; then
    echo "The project has no source code file yet."
else
    printf "%s\n" "${files[@]#*/}"
fi