5

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
1

2 Answers 2

5

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.

1
  • This won't break: set -f; find . -name '*.txt' -print0 | while IFS= read -r -d $'\0' file; do head -1 "$file" ;done . . . The set -f disables pathname expansion
    – Peter.O
    Oct 9, 2011 at 15:58
3

Check out the man page for your shell looking specifically at the IFS global variable.

Specifically, do this:

IFS=$(echo -en "\t\n\0")

5
  • echo $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? Oct 8, 2011 at 20:17
  • try hexdump -C there are actually 5 characters -c is displaying, the first is ' ' Oct 8, 2011 at 20:20
  • 2
    In short, the space character is included in the IFS variable. To prevent that reset IFS: IFS=$(echo -en "\t\n\0") Oct 8, 2011 at 20:21
  • 2
    @frogstarr78 - There's no need to use echo for that, in bash, just use $'\t\n\0'.
    – Chris Down
    Oct 8, 2011 at 20:53
  • @ChrisDown I didn't know. Thanx Oct 8, 2011 at 22:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .