'How to use cut to print only a single line of command output?

I've written a shell script for testing purposes which looks like this:

#!/bin/sh 
echo 'line 1\n line2\n line3'

I am trying to print only a single line by using the cut command like so:

echo $(./myScript.sh | cut -d$'\n' -f1)

In the above example, my intention is for it to print 'line1'. Replacing -f1 with -f2 would have it print 'line2' instead, or so I thought.

Instead, my output looks like this:

line1 line2 line3

Similarly, if I change the delimiter from $'\n' to something else, like so:

echo $(./myScript.sh | cut -d'e' -f1)

The output becomes:

lin lin lin

So it appears that it is printing the first field before any delimiters for each line instead of the entire output of myScript.sh as a whole. How can I get the cut command to work for the entire string instead of each individual line? Alternatively, what other command might work better for this purpose?

Thanks!



Solution 1:[1]

I have found a way of doing it that looks like this:

echo $(./myScript.sh | head -1)              # for the first line
echo $(./myScript.sh | head -2 | tail -1)    # for the second line
echo $(./myScript.sh | tail -1)    # for the third line

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community