2013-03-07 117 views
0

我有一個UNIX目錄中的某些文件:與排序的順序列表文件名 - ls命令

/opt/apps/testloc $ ls -mn 
test_1.txt 
test_2.txt 
test_11.txt 
test_12.txt 
test_3.txt 

我想與ls命令列出這一點,我需要基於在數字按排序順序輸出文件名的末尾。說輸出應該如下。

test_1.txt, test_2.txt, test_3.txt, test_11.txt, test_12.txt 

我無法得到提及。這些文件的名稱被視爲文本,它們如下進行分選,

test_11.txt, test_12.txt, test_1.txt, test_2.txt, test_3.txt 

我的命令ls –mn(我需要的輸出是逗號分隔格式,所以我用-m

我需要這是在我的下一個過程中以增量格式處理文件。

回答

2

如果你的版本sort可以做version sort-V則:

$ ls | sort -V | awk '{str=str$0", "}END{sub(/, $/,"",str);print str}' 
test_1.txt, test_2.txt, test_3.txt, test_11.txt, test_12.txt 

如果不這樣做:

$ ls | sort -t_ -nk2,2 | awk '{str=str$0","}END{sub(/,$/,"",str);print str}' 
test_1.txt, test_2.txt, test_3.txt, test_11.txt, test_12.txt 
+0

添加一個管道到'tr'\ n'',''得到一個csv-list,如OP所要求的。 – 2013-03-07 10:09:33

+0

現在你已經過分複雜化了:-)。 +1儘管如此, – 2013-03-07 10:33:54

+0

@Fredrik我不喜歡'tr'\ n'','',因爲它用'替換了後面的新行,'同樣希望'''不能用'tr'完成,所以通過使用'awk'你保存一個管道。 – 2013-03-07 10:38:49

-1

LS -al | sort + 4n:按照文件大小的升序列出 中的文件。即 按第5個字段排序,最先顯示 最小的文件。

1

你需要輸出爲特定格式告訴我你shouldn't be using ls。由於遞歸結果不是必需的,因此使用glob。

# Bash or ksh + GNU or other sort that handles NUL delimiters 

function sortFiles { 
    [[ -e $1 ]] || return 1 
    typeset a x 
    for x; do 
     printf '%s %s\0' "${x//[^[:digit:]]}" "$x" 
    done | 
    LC_ALL=C sort -nz - | { 
     while IFS= read -rd '' x; do 
      a+=("${x#* }") 
     done 
     typeset IFS=, 
     printf '%s\n' "${a[*]}" 
    } 
} 

sortFiles * 
0

如果所有的文件名包含正好一個_字符,然後是數字值,這種相對簡單的腳本將文件名由數字字段,並輸出它們的,[space]分隔列表(如ls -m一樣)排序:

ls -1 *_* | sort -t_ -n -k2 | sed ':0 N;s/\n/, /;t0' 

但是,如果有多個文件名_字符,要通過最後一個數字字段(不一定是文件名中的相同,如test_1_3.txttest_2.txt)對它們進行排序,則需要更爲複雜的腳本:

ls -1 *_* | 
awk -F '_' ' 
{ 
    key[gensub(/\..*$/, "", 1, $NF) "a" NR] = NR; 
    name[NR] = $0; 
} 
END { 
    len = asorti(key, keysorted, "@ind_num_asc"); 
    for (i = 1; i < len; i++) { 
    printf "%s, ", name[key[keysorted[i] ] ]; 
    } 
    printf "%s\n", name[key[keysorted[len] ] ]; 
}'