Something about DataStage, DataStage Administration, Job Designing,Developing, DataStage troubleshooting, DataStage Installation & Configuration, ETL, DataWareHousing, DB2, Teradata, Oracle and Scripting.
Tuesday, July 15, 2014
Handling Filename with Spaces in Linux
Spaces in Unix/Linux Filename is not a good habit as usually it is used as delimiter for field values rather than being in filename itself. In Linux, SPACE is used as a IFS ( Internal Field Separator) that is used for word splitting after expansion and to split lines into words with the read build in command. The default values of IFS is SPACE, TAB, NEW LINE.
This is why whenever we are doing something with File-name having spaces in Linux, we got error like..
: No such File or Directory
What if you got some files from a "Unix dumb" Server source, How you will handle the filename with spaces, Here are some simple ways to deal with it.
1. How to find the FileName having Spaces -
You can get the FileNames with 'ls' command but it will give you all the file names. 'Find' command will work here as we required with -exec option.
$ find ~ -name '* *' -exec ls {} \; #list the file name having spaces in Home dir
$ find ~ -name '* *' -exec ls -l{} \; #long list the file name having spaces in Home dir
2. Delete the FileName having Spaces -
We can use the same Find command to delete the files which is having the spaces. just replace the 'ls' with 'rm'.
$ find ~ -name '* *' -exec rm {} \;
3. Handle FileName having Spaces -
But this is not always the case or solution to just delete or list the files having spaces. We have to do some operation on File data, rename the Filename such a way which can be used easily. Best way to replace the " " (space) to "_" (underscore).
$ mv $filename $Newfilename
It's going to complain that it is getting more arguement to mv command, not the required two:
usage : mv [-f | -i |-n] [-v] source target
or
mv: target `File_name_with_spaces' is not a directory
In this case, the solution is to quote the filename variable:
$ mv "$filename" $Newfilename
It's always good to quote filenames to ensure that when the shell passes them to the command as argument, the filenames with embedded spaces are handles properly.
4. Sometime we need to do more than run one command on a filename. In this case, we would use a loop to process each file.
Code :
5. Replace "SPACE" to "UNDERSCORE" script
This script will help you to rename all the filename having spaces. Script will shrink and translate all the spaces into underscore for current directory.
Code :
Like the Facebook Page & join Group
https://www.facebook.com/DataStage4you
https://www.facebook.com/groups/DataStage4you
https://twitter.com/datastage4you
For WHATSAPP group , drop a msg to 91-88-00-906098
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment