Reputation: 539
I am very new to shell script and trying to learn it.
My use case with Shell script is that I need to replace a particular string with an empty string on all the files content which are inside a folder. The following is my folder structure.
-> RootFolder
-> applications
-> a.app
-> layout
-> Account-Service Plus Account Layout.layout
-> Address-Service Plus Address Layout.layout
-> classes
-> A.cls
-> B.cls
I am getting below error on files which has the name with spaces. Can anyone point me what I have missed over there?
../RootFolder/layouts/Account-Service
sed: can't read ../RootFolder/layouts/Account-Service: No such file or directory
Plus
sed: can't read Plus: No such file or directory
Account
sed: can't read Account: No such file or directory
Layout.layout
My script is,
for d in $(find ../RootFolder -maxdepth 2 -type f)
do
echo "$d"
sed -i "s/test/''/g" "$d"
done
Upvotes: 1
Views: 3495
Reputation: 29050
If you have spaces in your file names (which is not a very good idea if you want to automate your processing) you must code everything with this in mind.
for d in $(find ../RootFolder -maxdepth 2 -type f)
will treat each space-separated word independently, even if they are parts of the same file name. A more robust solution consists in using the -print0
option of find
, that uses the null character as output separator, and write your loop such that it also uses the null character as the separator:
find ../RootFolder -maxdepth 2 -type f -print0 | \
while IFS= read -r -d '' d; do
echo "$d"
sed -i "s/test/''/g" "$d"
done
The read
command is used with:
IFS=
(empty Input Field Separator) to preserve leading and trailing spaces,-r
option to preserve backslashes and-d ''
option to use the null character as the word separator.With this, find
can output any crazy file names, they should be passed to the while
loop in the d
shell variable, unmodified and one at a time... Unless your file system allows null characters in file names (I don't know any such file system but I don't know them all).
Upvotes: 2