[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

bash read and field separator



On 07/12/2022 19:18, Greg Wooledge wrote:

rlart() {
   local day time path
   find "${1:-.}" -type f -printf '%T@ %TY-%Tm-%Td %TT %p\0' |
     sort -zn |
     while read -rd '' _ day time path; do
       printf '%s %s %s\n' "$day" "${time%.*}" "$path"
     done
}

I was not aware of the "read -d ''" feature that allows to work with null-terminated records, so thank you for the hint. However the read command strips leading and trailing spaces and newlines from path. What is the best way to preserve them? I have tried slash (a character disallowed in file names) instead of space as field separator:

printf 'a///1/1\n\000b/ 2/\000c/3/\000d/4//\000' |
  while IFS='/' read -r -d '' num path ; do
    printf '%s %q\n' "$num" "$path" ;
  done
a $'//1/1\n'
b \ 2
c 3
d 4//

No problem with spaces, leading "//" are preserved, but single trailing slash is removed after "3".

Another question is if "$@" instead of "${1:-.}" may cause any problem.


Reply to: