What is equivalent of head/tail command to show head/tail or a line?
head2 -2 "abcdefghijklmnopqrstuvwxyz"
=> ab
tail2 -2 "abcdefghijklmnopqrstuvwxyz"
=> yz
What is equivalent of head/tail command to show head/tail or a line?
head2 -2 "abcdefghijklmnopqrstuvwxyz"
=> ab
tail2 -2 "abcdefghijklmnopqrstuvwxyz"
=> yz
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
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}
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
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