1

Suppose I have a Bash object $TEST defined like this:

> TEST=`echo -e "hello\\nworld"`
> echo $TEST 
hello 
world

Using just echo, how do I output 'hello' from $TEST? How do I output 'world' from TEST? (no other commands allowed). I have trouble getting it to recognize the newline character.

3
  • 1
    Err... "no other commands allowed"? Is this homework of some kind?
    – DevSolar
    Commented Apr 5, 2016 at 12:37
  • Actually no, I just wanted to rule out other solutions that use a combination of commands (like 'head') with pipes, for my own learning benefit.
    – KDC
    Commented Apr 5, 2016 at 12:58
  • You might want to add a line to that end to future questions. Homework questions attract a different kind of answer. ;-)
    – DevSolar
    Commented Apr 5, 2016 at 13:01

2 Answers 2

3

Using bash parameter expansion:

$ echo "$TEST"
hello
world

$ echo "${TEST%$'\n'*}"
hello

$ echo "${TEST#*$'\n'}"
world
0
0

The built-in read command can extract one line at a time.

$ { IFS= read -r line1; IFS= read -r line2; } <<< "$TEST"
$ echo "$line1"
hello
$ echo "$line2"
world

Not the answer you're looking for? Browse other questions tagged or ask your own question.