简体   繁体   English

如何在文件中的unix中打印第一行的第一个单词和最后一行的最后一个单词

[英]How to print first word of first line and last word of last line in unix in a file

Suppose there is a file file1.c It has 100 lines . 假设有一个文件file1.c它有100行。 I need to print first word and last word of that file. 我需要打印该文件的第一个单词和最后一个单词。

first word: head -1 file1.c | cut -d" " -f 1 第一个字: head -1 file1.c | cut -d" " -f 1 head -1 file1.c | cut -d" " -f 1

last word: tail -1 file1.c | rev | cut -d" " -f 1 | rev 最后一句话: tail -1 file1.c | rev | cut -d" " -f 1 | rev tail -1 file1.c | rev | cut -d" " -f 1 | rev

head -1 print first line head -1打印第一行

-d stands for delimeter in this case " " (space) -d代表在这种情况下的分隔符" " (空格)

-f 1 first field -f 1第一个字段

tail -1 print last line tail -1打印最后一行

rev reverse the input - in this case first rev cause that line is "mirrored" so last field is now first, so we can cut it. rev反向输入-在这种情况下,第一个rev导致该行被“镜像”,因此最后一个字段是现在第一,所以我们可以cut它。 Second rev reverse/mirror back the desired field so its readable 第二rev反向/镜像回所需的字段,以便它的可读

awk 'NR==1{print $1} END{print $NF}' file1.c

NR==1 : means, line number should be 1. END{} : This block will get executed at the last line of the file. NR==1 :表示行号应为1. END{} :此块将在文件的最后一行执行。 $1 : First column $NF : last column. $1 :第一栏$NF :最后一栏。 Hope it helps. 希望能帮助到你。

Translate the file to one line and remove everything between the first and last space: 将文件转换为一行并删除第一个和最后一个空格之间的所有内容:

tr -d "\n" < file1.c| sed 's/ .* / /'

When you file starts or ends with a space, this won't work. 当您以文件开头或以空格结束时,这将无效。 You can fix that with the more complicated 你可以用更复杂的方法解决这个问题

tr -d "\n" < file1.c| sed -r 's/[ ]*([^ ]+).*([^ ]+)/\1 \2/'

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

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