Linux shell 腳本小記2

1、從文件讀取
while read line
do
    echo "line=$line"
done < file.txt

2、將字符串轉換爲數組,並進行遍歷
str="html, css, javascript, java, php, go, python"
arr=(${str//,/ })
for item in ${arr[@]}
do
    echo "item=$item"
done

3、將目錄轉換爲字符串
ls | xargs -d'\t' echo |awk 'BEGIN{i=0;} { if(i > 0){ printf(",");} i++;printf("%s", $0);}'

4、遞歸

function find(){
    local dir=$1
    local arr=( $(ls $dir) )

    for item in ${arr[@]}
    do
        local path="$dir/$item"
        if [ -L $path ]
        then
            echo "ln $path"
            find $path
        elif [ -d $path ]
        then
            echo "dir $path"
            find $path
        else
            echo "file path=$path, dir=${path%/*}, filename=${path##*/}"
        fi
    done
}

備註:
獲取當前路徑下的目錄:${path%/*}
獲取當前路徑下的文件名:${path##*/}
相關文章
相關標籤/搜索