2011-01-24 52 views
0

我想输出'filename1','filename2' ,'filename3' ....如何使用awk引用文件名?

我使用awk ..但不知道如何打印文件名后的最后一个步骤。 它打印我, '文件名===>我所需要的,' 文件名”

ls -ltr | grep -v ^d | sed '1d'| awk '{print "," sprintf("%c", 39) $9}' 

提前感谢!

+0

难道你不会像输出第一个报价一样输出第二个报价吗?更严重的是,你对这个名为'Thomas O'Malley'的文件有什么看法? – 2011-01-24 15:07:16

+2

当我看到“ls -l”输出的第九列时,“我想哭。例如,尝试`alias ls =“ls -T”`然后尝试命令。我希望你也在做其他可怕的事情:为什么你觉得需要生成一个逗号分隔的引用文件名列表?也许你的目的是合法的,但是这个味道就像“带有空格的文件名不断搞砸我的脚本,我知道,我会制作一个引用列表。” – Sorpigal 2011-01-24 15:31:08

+1

请参阅[为什么不应该解析ls的输出](http://mywiki.wooledge.org/ParsingLs)。 – 2011-01-24 16:01:04

回答

2

可以使用find命令:

find . -maxdepth 1 -type f -printf "'%f'," | sed s/,$// 
1

,如果你有红宝石(1.9+)

ruby -e 'puts Dir["*"].select{|x|test(?f,x)}.join("\47,\47")' 

其他

find . -maxdepth 1 -type f -printf '%f\n' | sed -e ':a N' -e "[email protected]\[email protected]','@" -e 'b a' 
0

纯庆典(大概POSIX SH,太):

comma= 
for file in * ; do 
    if [ ! -d "$file" ] ; then 
     if [ ! -z $comma ] ; then 
      printf "," 
     fi 
     comma=1 
     printf "'%s'" "$file" 
    fi 
done 

文件的名称中'不记账,但没有其他人在做,要么。假设用\转义是正确的,你可以做。

comma= 
for file in * ; do 
    if [ ! -d "$file" ] ; then 
     if [ ! -z $comma ] ; then 
      printf "," 
     fi 
     comma=1 
     printf "'%s'" "${file//\'/\'}" 
    fi 
done 

但有些CSV系统会要求你跟着写''代替,这将是

printf "'%s'" "${file//\'/''}" 
0

让我们假设你正在处理一些其他的数据之外的ls输出。

$ printf "hello\ngoodbye\no'malley\n" | awk '{gsub("\047","\047\\\047\047",$1);printf "%s\047%s\047",comma,$1; comma=","}END{printf "\n"}' 
'hello','goodbye','o'\''malley' 
0

这个变种的工作正常,但我认为应该有更优雅的方式来做到这一点。

ls -1 $ 1 |切“-d”。 -f1 | awk'{printf“,”sprintf(“%c”,39)$ 1 sprintf(“%c”,39)“\ n”}'| sed'1 s /,* //'