Reputation: 375
I understand that one technique for dealing with spaces in filenames is to enclose the file name with single quotes: "'"
.I have a directory and a filename with space. I want a shell script to read all the files along with the posted time and directory name. I wrote the below script:
#!/bin/bash
CURRENT_DATE=`date +'%d%m%Y'`
Temp_Path=/appinfprd/bi/infogix/IA83/InfogixClient/Scripts/IRP/
find /bishare/IRP_PROJECT/SFTP/ -type f | xargs ls -al > $Temp_Path/File_Posted_$CURRENT_DATE.txt
which is partially working. It is not working for the directory and files that has a space in it.
Upvotes: 0
Views: 281
Reputation: 770
You can change the IFS variable for a moment (Internal Fields Separator):
#!/bin/bash
# Backing up the old value of IFS
OLDIFS="$IFS"
# Making newline the only field separator - spaces are no longer separators
# NOTE that " is the last character in line and the next line starts with "
IFS="
"
CURRENT_DATE=`date +'%d%m%Y'`
Temp_Path=/appinfprd/bi/infogix/IA83/InfogixClient/Scripts/IRP/
find /bishare/IRP_PROJECT/SFTP/ -type f | xargs ls -al > $Temp_Path/File_Posted_$CURRENT_DATE.txt
# Restore the original value of IFS
IFS="$OLDIFS"
Upvotes: 0
Reputation: 361565
Use find -print0 | xargs -0
to reliably handle file names with special characters in them, including spaces and newlines.
find /bishare/IRP_PROJECT/SFTP/ -type f -print0 |
xargs -0 ls -al > "$Temp_Path/File_Posted_$CURRENT_DATE.txt"
Alternatively, you can use find -exec
which runs the command of your choice on every file found.
find /bishare/IRP_PROJECT/SFTP/ -type f -exec ls -al {} + \
> "$Temp_Path/File_Posted_$CURRENT_DATE.txt"
In the specific case of ls -l
you could take this one step further and use the -ls
action.
find /bishare/IRP_PROJECT/SFTP/ -type f -ls > "$Temp_Path/File_Posted_$CURRENT_DATE.txt"
You should also get in the habit of quoting all variable expansions like you mentioned in your post.
Upvotes: 1