0

Say I have a directory with three files with names including spaces: a b, c d, and e f. And I want to use vi to edit the first two files. The bash command I want is

vi "a b" "c d"

I also want to get the first two lines of ls command using head, such that I can substitute the first command's parameters:

ls | head -n 2

However, if I run vi $(ls | head -n 2), it is equivalent to vi a b c d, which is not what I want, because the output inside $() is splitted by space and newline. Is there any way to split the output only by newline?

1

1 Answer 1

2

Is there any way to split the output only by newline?

Yes, set IFS to just a newline (by default it contains a space, a tab and a newline):

IFS=$'\n'
vi $(ls | head -n 2)

($'' is nonstandard but works in Bash/ksh/zsh, and much prettier than the alternatives.)


That said, you still have the problem that the filenames might contain glob characters. To disable globbing, you'd need to use set -f first (and set +f after to re-enable it). And also, if your filenames contain newlines, that won't work, but I suppose you knew that.

You must log in to answer this question.

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