Reputation: 81
The question is: Display the and character from each line of text.
This was my code:
while read line
do
a=`echo $line | cut -c 2`
b=`echo $line | cut -c 7`
echo -n $a
echo $b
done
The problem is that when the first character is a space, it does not print the space. For example,
Input:
A big elephant
Expected output:
e
My output:
e
How can this be fixed?
Upvotes: 0
Views: 1902
Reputation: 363
You need to quote the variables. When bash is expanding $a, the space isn't printed by echo, since it isn't seen as an argument.
A command can have plenty of trailing spaces, but since bash use spaces by default to separate commands and arguments, any extra spaces will be ignored, unless explicitly part of an argument (either using quotes or escaping).
For example:
=> echo a # Argument without spaces works (at least in this case)
a
=> echo a # Two spaces between, unquoted spaces are ignored
a
=> echo " a" # Quotes make the space part of the argument
a
=> echo a # Arguments can have many spaces between them
a
=> echo # No quotes or spaces, echo sees no arguments, doesn't print anything
=> echo " " # Space is printed (changed to an underscore, wouldn't actually be visible)
_
=>
This is also why spaces have to be escaped in filenames, unless they are quoted:
=> touch file 1 # Makes two files: "file" and "1"
=> touch "file 1" # Makes one file: "file 1"
=> touch file\ 1 # Makes one file: "file 1"
Your final code would be:
while read line
do
a=`echo $line | cut -c 2`
b=`echo $line | cut -c 7`
echo -n "$a"
echo "$b"
done
Upvotes: 6
Reputation: 81
I have fixed it too
while read line
do
a=`echo $line | cut -c 2`
b=`echo $line | cut -c 7`
echo "$a$b"
done
Upvotes: 0
Reputation: 92904
Simple variations:
--- with pure bash
(basing on slices):
s="A big elephant"
echo "${s:1:1}${s:8:1}"
e
--- with bash
+ cut
:
s="A big elephant"
cut -c 2,7 <<<"$s"
e
Upvotes: 1