How to tell find command to escape space character

2019-07-16 19:13发布

I have a single line find command, which recursively checks and prints out the size, owner and name of a specific file type which are created in a specific time frame. But in the result, the filename column is given until the first space character in the directory or file name. Any idea to fix this problem right in this single command without writing any loop in the bash? Thanks!

here is the command:

find /path/to/dist -type f -iname "*.png" -newermt 2015-01-01 ! -newermt 2016-12-31 -ls | sort -k5 | sort -k5 | awk '{print $5"\t"$7"\t"$11}'

标签: bash find
4条回答
Rolldiameter
2楼-- · 2019-07-16 19:39

Well thanks to Arno's input, the following line does the job. I used exec (-exec ls -lh {} \;) to make the size human readable:

find /Path/To/Dest/ -type f -iname "*.pdf" -newermt 2015-01-01 ! -newermt 2016-12-31 -exec ls -lh {} \; |sed 's/\\ /!!!/g' | sort -k5 | awk '{gsub("!!!"," ",$11);print $3"\t"$5"\t"$9}'
查看更多
3楼-- · 2019-07-16 19:55

Try changing your awk command to this :

awk '{$1=$2=$3=$4=$6=$8=$9=$10="" ; print$11}'

So that the whole command becomes this :

find /path/to/dist -type f -iname "*.png" -newermt 2015-01-01 ! -newermt 2016-12-31 -ls | sort -k5 | awk '{$1=$2=$3=$4=$6=$8=$9=$10="" ; print$0}'

This leaves some extra spaces at the beginning of the line, hopefully it works for your purpose.

I have removed the second instance of sort, as it sorts on the same key as the first, which does not seem likely to do anything.

查看更多
走好不送
4楼-- · 2019-07-16 19:55

I found the following solution. You hide the space in filename. I did it with a sed, I used a strange chain "!!!" to replace "\ ". Then I replace it in awk command. Here is the command I used for my tests:

find . -type f -iname "*.pdf" -newermt 2015-01-01  -ls |sed 's/\\ /!!!/g' | sort -k5 | awk '{gsub("!!!"," ",$11);print $5"\t"$7"\t"$11}'
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-07-16 19:55

The -print0 action of find is probably the starting point. From find's manual page:

   -print0
          True;  print  the  full file name on the standard output,
          followed by a null  character  (instead  of  the  newline
          character that -print uses).  This allows file names that
          contain newlines or other types of white space to be cor‐
          rectly interpreted by programs that process the find out‐
          put.  This option corresponds to the -0 option of xargs.

But find has the nice printf action that is even better:

find /path/to/dist -type f -iname "*.png" -newermt 2015-01-01 ! -newermt 2016-12-31 -printf "%u\t%s\t%p\n" | sort

probably does the job.

查看更多
登录 后发表回答