2012-09-01 36 views
0

我目前正在研究GNU/Linux系統上的一些C++代碼,並且我的源代碼文件夾中填充了.cpp文件和.h文件。Bash腳本,用於在BASH外殼中以特定格式列出目錄中的文件

一般對於這段代碼,每個.cpp文件都有對應的.h頭文件,但不一定是 ,反之亦然。在下面的輸出--表示沒有對應的.cpp文件列出的頭文件

我想要寫一個bash腳本來做到這一點,比如在我的.bashrc/.zshrc中定義一個額外的標誌,例如文件列表的 發生在這種格式。說我有7個文件,有的.cpp有的.h

$ listscript 
hello1.cpp hello1.h 
hello2.cpp hello2.h 
    --  hello3.h 
hello4.cpp hello4.h  
+0

我想你寧願寫一個bash腳本來做到這一點,而不是試圖讓ls來做到這一點。 – Joey

+0

是的,bash腳本解決方案也適用於我。 – smilingbuddha

+0

其實,你爲什麼不用C++編寫這樣的工具...... – grawity

回答

1
#!/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 
+0

謝謝。這似乎是一個更好的解決方案。 – smilingbuddha

0

如何(在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 
+1

'for $ in $(ls ...)'是[bad](http://mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28 ls_.2A.mp3.29)。所以[使用'&& ||'](http://mywiki.wooledge.org/BashPitfalls#cmd1_.26.26_cmd2_.7C.7C_cmd3)作爲三元運算符,或者[不要放引號](http://mywiki.wooledge .org/BashPitfalls#cp_.24file_.24target)圍繞變量。 – grawity

0

這是我在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 
1

由於每.h文件可能有或沒有相應的.cpp文件, 只是遍歷所有.h文件。對於每一個,您都可以檢查 對應的.cpp文件是否存在,如果不存在則使用「---」。

for fh in *.h; do 
    fcpp=${fh/%.h/.cpp} 
    [ -f "$fcpp" ] || fcpp="---" 
    printf "%s\t%s\n" "$fcpp" "$fh" 
done 
相關問題