Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash/Shell - paths with spaces messing things up

Tags:

find

bash

awk

I have a bash/shell function that is supposed to find files then awk/copy the first file it finds to another directory. Unfortunately if the directory that contains the file has spaces in the name the whole thing fails, since it truncates the path for some reason or another. How do I fix it?

If file.txt is in /path/to/search/spaces are bad/ it fails.

dir=/path/to/destination/ | find /path/to/search -name file.txt | head -n 1 | awk -v dir="$dir" '{printf "cp \"%s\" \"%s\"\n", $1, dir}' | sh

cp: /path/to/search/spaces: No such file or directory

*If file.txt is in /path/to/search/spacesarebad/ it works, but notice there are no spaces. :-/

like image 562
Ned Schneebly Avatar asked Jan 30 '26 20:01

Ned Schneebly


1 Answers

Awk's default separator is white space. Simply change it to something else by doing:

awk -F"\t" ...

Your script should look like:

dir=/path/to/destination/ | find /path/to/search -name file.txt | head -n 1 | awk -F"\t" -v dir="$dir" '{printf "cp \"%s\" \"%s\"\n", $1, dir}' | sh

As pointed by the comments, you don't really need all those steps, you could actually simply do (one-liner):

dir=/path/to/destination/ && path="$(find /path/to/search -name file.txt | head -n 1)" && cp "$path" "$dir"

Formated code (that may look better, in this case ^^):

dir=/path/to/destination/
path="$(find /path/to/search -name file.txt | head -n 1)"
cp "$path" "$dir"

The "" are used to assign the entire content of the string to the variable, causing the separator IFS, which is a white space by default, not to be considered over the string.

like image 115
Rubens Avatar answered Feb 01 '26 13:02

Rubens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!