Spaces as line breaks from inline for loop command
6,404
Solution 1
Check out the man page for your shell looking specifically at the IFS global variable.
Specifically, do this:
IFS=$(echo -en "\t\n\0")
Solution 2
Your command substitution induces word splitting on its output, based on IFS. Specifically, in this case it is splitting on spaces. Do not parse the output of find
. Instead, do this:
for file in *.txt; do
head -1 "${file}"
done
The Wooledge wiki also has some good information on this issue here.
Related videos on Youtube
Author by
Christopher O'Neil
Updated on September 18, 2022Comments
-
Christopher O'Neil almost 2 years
Someone care to enlighten me as to why the spaces in the first command seem to be interpreted as line breaks? Also occurs substituting print for echo.
$for l in $( find *.txt -exec head -1 {} \; ); echo $l;
9.16.11 09:20 9.19.11 18.41 9.21.11 07:15
$find *.txt -exec head -1 {} \;
9.16.11 09:20 9.19.11 18.41 9.21.11 07:15
-
Christopher O'Neil over 12 yearsecho $IFS | hexdump -c Has revealed $IFS to contain "\t \n \0 \n" But I'm still confused as to what I have to to keep the spaces from being interpreted as new lines?
-
frogstarr78 over 12 yearstry hexdump -C there are actually 5 characters -c is displaying, the first is ' '
-
clerksx over 12 years@frogstarr78 - There's no need to use echo for that, in bash, just use
$'\t\n\0'
. -
frogstarr78 over 12 years@ChrisDown I didn't know. Thanx
-
Peter.O over 12 yearsThis won't break:
set -f; find . -name '*.txt' -print0 | while IFS= read -r -d $'\0' file; do head -1 "$file" ;done
. . . Theset -f
disables pathname expansion