开发者

Bash: How to avoid blank at the beginning of a line?

Given such a command in bash:

echo -e "a b "{1..3}" d e\n"
a b 1 d e
 a b 2 d e
 a b 3 d e

the output of line 2... starts with a blank. Why is that? Where does it come from? How can I avoid it?

I do know how to get rid of it with sed or something else, but I would prefer to avoid it in the first place.

I've only mentioned it, together with {..}-Syntax. Are there other, similar cases, without it?

update:

A useful workaround is, to remove the first letter with backspace:

echo -e "\ba b "{1..3}" d e\n"

or, as Jared Ng suggests:

echo -e "\ra b "{1..3}开发者_StackOverflow" d e\n"

update 2:

We get rid of leading newlines with:

echo -e "\na b "{1..4}" d e" | sed '1d'
echo -e "\na b "{1..4}" d e" | tail -n +2

or trailing:

echo -e "\ba b "{1..3}" d e\n" | sed '$d'
echo -e "\ba b "{1..3}" d e\n" | head -n 3


echo -e "\ra b "{1..3}" d e\n"

Fixes it for me. Output:

a b 1 d e
a b 2 d e
a b 3 d e

(\r is the carriage return -- it brings the caret back to the beginning of the line, preventing the space)

Why does bash do this? Run echo "abc"{1..3}. You'll see that bash outputs: abc1 abc2 abc3. Notice the spaces in between? {1..3} expands the expression, delimited by spaces. When you use a newline, as in echo "abc"{1..3}"\n", bash keeps those spaces and simply adds a newline as requested. Those are what show up in the output.


The {...} expands to a sequence of space-delimited alternatives, so you have in effect

echo "a b "1" d e\n" "a b "2" d e\n" "a b "3" d e\n"

The spaces after \n are the spaces you're seeing in the output.

You can try to move \n to the beginning of your string, like in

echo -e "\na b "{1..3}" d e"

Update

Another method (untested, sorry)

 printf "%s\n" "a b "{1..3}" d e"


Brace expansion was designed to generate a list of entries to be used as arguments to commands. The generated entries are always space-delimited, hence the extra spaces.

To use the {1..3} syntax as is, you'll need to use a command that can treat each generated entry as an independent arg (echo simply prints them out as it sees it). A good option here is printf (as suggested by @glenn in the comments above).

[me@home]$ printf "%s\n" "a b "{1..3}" d e"
a b 1 d e
a b 2 d e
a b 3 d e
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜