简体   繁体   English

等效于头/尾命令以显示头/尾或一条线

[英]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 如果要整个流的第一个/最后一个字符,则相当于headtail

$ 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. head不会输出换行符,因为它仅输出前两个字符。 tail counts newline as a character, so we need to output 3 to get the last two. tail将换行符视为字符,因此我们需要输出3以获得最后两个字符。 Reformatting the commands to take arguments as in your example is trivial and I leave that to OP. 重新格式化命令以接受您的示例中的参数是微不足道的,我将其留给OP。

You can use cut if you want first characters of each line: 如果需要每行的第一个字符,可以使用cut

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

and use rev | cut | rev 并使用rev | cut | rev rev | cut | rev rev | cut | rev mnemonic to get the last characters: rev | cut | rev助记符以获取最后一个字符:

$ 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. 如果要输出10个以上的字符,则不能使用cut。 Y ÿ

You could use cut https://linux.die.net/man/1/cut 您可以使用cut https://linux.die.net/man/1/cut

But you don't need it as we have bash substring extraction: 但是您不需要它,因为我们有bash子字符串提取:

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

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

You can directly use bash substring extraction syntax, no need to use external commands : 您可以直接使用bash子字符串提取语法,而无需使用外部命令

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

With sed : 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: 根据您的发行版,您可以使用cut命令:

Head: 头:

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

Yields: He 产量: 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. 产量: g.


2 is the amount of characters to print 2是要打印的字符数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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