1

What is equivalent of head/tail command to show head/tail or a line?

head2 -2 "abcdefghijklmnopqrstuvwxyz"

=> ab

tail2 -2 "abcdefghijklmnopqrstuvwxyz"
=> yz
gacopu
  • 594
  • 3
  • 21

4 Answers4

2

It's equivalent to head and tail if you want first/last characters of the whole stream

$ head -c2 <<<"abcdefghijklmnopqrstuvwxyz"
ab<will not output a newline>

$ tail -c3 <<<"abcdefghijklmnopqrstuvwxyz"
yz<newline>

The head will not output a newline, as it outputs only first two characters. tail counts newline as a character, so we need to output 3 to get the last two. Reformatting the commands to take arguments as in your example is trivial and I leave that to OP.

You can use cut if you want first characters of each line:

$ cut -c-2 <<<"abcdefghijklmnopqrstuvwxyz"$'\n''second line'
ab
se

and use rev | cut | rev mnemonic to get the last characters:

$ rev <<<"abcdefghijklmnopqrstuvwxyz"$'\n''second line' | cut -c-2 | rev
yz
ne

If you want to output more than 10 characters you can't use cut. Y

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
0

You could use cut https://linux.die.net/man/1/cut

But you don't need it as we have bash substring extraction:

export txt="abcef"
echo head: ${txt:0:2}
echo tail: ${txt: -2}

https://www.tldp.org/LDP/abs/html/string-manipulation.html

olivecoder
  • 2,858
  • 23
  • 22
  • This was the first answer and was already pointing to cut and bash extraction. Could you the @donwvoter say why the downvote, please? Have not the others also improved progressively their answers? – olivecoder Apr 01 '19 at 07:34
  • I downvoted your initial answer - it was a link only answer. I saw your comment by chance, since I left this page open - next time please adhere to the answering guidelines (see meta) from the initial draft as most of us do not waste timing explaining our up/down votes. In addition, there is little chance someone who voted you will come back to check for an improvement. If you would have just given examples to what you linked to (in the original version), I would have probably upvoted you for being first. – kabanus Apr 01 '19 at 08:22
0

You can directly use bash substring extraction syntax, no need to use external commands:

$ input="abcdefghijklmnopqrstuvwxyz"; echo ${input: -2}
yz
$ input="abcdefghijklmnopqrstuvwxyz"; echo ${input:0:2}
ab

With sed:

echo abcdefghijklmnopqrstuvwxyz | sed -E 's/^(..).*/\1/'; echo abcdefghijklmnopqrstuvwxyz | sed -E 's/^.*(..)$/\1/';
ab
yz
Allan
  • 12,117
  • 3
  • 27
  • 51
0

Depending on your distro, you can use the cut command:

Head:

echo "Hello! This is a test string." | cut -c1-2

Yields: He


For tail you basically do the same thing, but you reverse the string first, cut it, and reverse it again.

Tail:

echo "Hello! This is a test string." | rev | cut -c1-2 | rev

Yields: g.


2 is the amount of characters to print

NullDev
  • 6,739
  • 4
  • 30
  • 54