开发者

How to quote file name using awk?

I want output 'filename1'开发者_开发知识库,'filename2' ,'filename3' ....

I m using awk ..but no idea how to print last quoate after filename. It printing me ,'filename ===>I need ,'filename'

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

Thanks in advance!


You can use the find command as:

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


if you have Ruby(1.9+)

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

else

find . -maxdepth 1 -type f -printf '%f\n' | sed -e ':a N' -e "s@\n@','@" -e 'b a'


Use the printf function http://www.gnu.org/manual/gawk/html_node/Basic-Printf.html


Pure bash (probably posix sh, too):

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

Files with ' in the name are not accounted for, but nobody else has been doing that either. Presuming that escaping with \ is correct you could do.

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

But some CSV systems would require you to follow write '' instead, which would be

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


Let's pretend that you're processing some other data besides the output of 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'


This variant works fine but I think there should be more elegant way to do it.

ls -1 $1 | cut -d'.' -f1 | awk '{printf "," sprintf("%c", 39) $1 sprintf("%c", 39) "\n" }'| sed '1 s/,*//'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜