在 txt 文件的每一行中打印第一个单词 unix bash
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19145419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
printing first word in every line of a txt file unix bash
提问by ap1993
So I'm trying to print the first word in each line of a txt file. The words are separated by one blank.
所以我试图在 txt 文件的每一行中打印第一个单词。单词之间用一个空格隔开。
cut -c 1 txt file
Thats the code I have so far but it only prints the first character of each line. Thanks
这就是我到目前为止的代码,但它只打印每行的第一个字符。谢谢
回答by Barmar
To print a whole word, you want -f 1
, not -c 1
. And since the default field delimiter is TAB rather than SPACE, you need to use the -d
option.
要打印整个单词,您需要-f 1
,而不是-c 1
。由于默认的字段分隔符是 TAB 而不是 SPACE,您需要使用该-d
选项。
cut -d' ' -f1 filename
To print the last two words not possible with cut
, AFAIK, because it can only count from the beginning of the line. Use awk
instead:
cut
AFAIK无法打印最后两个单词,因为它只能从行首开始计数。使用awk
来代替:
awk '{print $(NF-1), $NF;}' filename
回答by CS Pei
you can try
你可以试试
awk '{print }' your_file
回答by kojiro
read word _ < file
echo "$word"
What's nice about this solution is it doesn't read beyond the first line of the file. Even awk, which has some very clean, terse syntax, has to be explicitly toldto stop reading past the first line. read
just reads one line at a time. Plus it's a bash builtin (and a builtin in many shells), so you don't need a new process to run.
这个解决方案的好处是它不会超出文件的第一行。即使 awk 具有一些非常干净、简洁的语法,也必须明确告知停止阅读第一行。read
一次只读一行。此外,它是一个 bash 内置函数(以及许多 shell 中的内置函数),因此您不需要运行新进程。
If you want to print the first word in each line:
如果要打印每行的第一个单词:
while read word _; do printf '%s\n' "$word"; done < file
But if the file is large then awk or cut will win out for reading every line.
但是如果文件很大,那么 awk 或 cut 将胜出读取每一行。
回答by termux overflow
You can use:
您可以使用:
cut -d\ -f1 file
Where:
在哪里:
- -d is the delimiter (here using
\
for a space) - -f is the field selector
- -d 是分隔符(此处
\
用于空格) - -f 是字段选择器
Notice that there is a space
after the \
.
请注意,在space
之后有一个\
。
回答by Alex Howansky
-c
is for characters, you want -f
for fields, and -d
to indicate your separator of space instead of the default tab:
-c
用于字符,您需要-f
字段,并-d
指示您的空格分隔符而不是默认选项卡:
cut -d " " -f 1 file