简体   繁体   中英

Equivalent of head/tail command to show head/tail or a line

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 rev | cut | rev 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}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM