[英]Bash script for listing the files in a directory in a specific format witht the BASH shell
I am currently working on some C++ code on a GNU/Linux system and my source-code folder is filled with .cpp files and .h files. 我目前正在GNU / Linux系统上编写一些C ++代码,我的源代码文件夹中填充了.cpp文件和.h文件。
In general for this code, every .cpp
file has a corresponding .h
header file, but not necessarily vice versa. 通常对于此代码,每个
.cpp
文件都有一个相应的.h
头文件,但不一定相反。 In the output below --
indicates that there is no corresponding .cpp file for the listed header file 在下面的输出中
--
表示列出的头文件没有相应的.cpp文件
I would like to either write a bash script to do this by say defining an extra flag in my .bashrc / .zshrc , such that the listing of the files occurs in this format. 我想编写一个bash脚本来执行此操作,方法是在我的.bashrc / .zshrc中定义一个额外的标志,这样文件的列表就会以这种格式出现。 Say I have 7 files, some
.cpp
and some .h
假设我有7个文件,一些
.cpp
和一些.h
$ listscript
hello1.cpp hello1.h
hello2.cpp hello2.h
-- hello3.h
hello4.cpp hello4.h
#!/usr/bin/env bash
declare files=(*)
declare file= left= right= width=10
declare -A listed=()
for file in "${files[@]}"; do
if [[ $file == *.h ]]; then
continue
elif (( ${#file} > width )); then
width=${#file}
fi
done
for file in "${files[@]}"; do
if [[ ${listed[$file]} == 1 ]]; then
continue
elif [[ $file == *.cpp ]]; then
left=$file right=${file%.cpp}.h
elif [[ $file == *.h ]]; then
left=${file%.h}.cpp right=$file
else
left=$file right=
fi
[[ $left ]] && listed["$left"]=1
[[ $right ]] && listed["$right"]=1
[[ -e $left ]] || left='--'
[[ -e $right ]] || right='--'
printf "%-*s %s\n" "$width" "$left" "$right"
done
Since every .h
file may or may not have a corresponding .cpp
file, just iterate over all .h
files. 由于每个
.h
文件可能有也可能没有相应的.cpp
文件,只需迭代所有.h
文件。 For each one, you can check if the corresponding .cpp
file exists and use "---" if not. 对于每一个,您可以检查相应的
.cpp
文件是否存在,如果不存在则使用“---”。
for fh in *.h; do
fcpp=${fh/%.h/.cpp}
[ -f "$fcpp" ] || fcpp="---"
printf "%s\t%s\n" "$fcpp" "$fh"
done
How about (in bash
): 怎么样(在
bash
):
for f in $(ls -1 *.{cpp,h} | sed -e 's/.cpp//;s/.h//' | sort -u)
do
[ -f "${f}.cpp" ] && printf "%s " "${f}.cpp" || printf " -- "
[ -f "${f}.h" ] && printf "%s" "${f}.h" || printf " -- ";
printf "\n"
done
Here's my attempt in bash: 这是我在bash中的尝试:
#!/bin/bash
# run like this:
# ./file_lister DIRECTORY
for i in $1/*.h
do
name=`basename $i .h`
if [ -e $name.cpp ]
then
ls $name.*
else
echo "-- " `basename $i`
fi
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.