printing first word in every line of a txt file un

2020-06-07 19:24发布

问题:

So I'm trying to print the first word in each line of a txt file. The words are separated by one blank.

cut -c 1 txt file 

Thats the code I have so far but it only prints the first character of each line. Thanks

回答1:

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.

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:

awk '{print $(NF-1), $NF;}' filename


回答2:

you can try

awk '{print $1}' your_file


回答3:

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 told to 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.

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.



回答4:

You can use:

cut -d\  -f1 file

Where:

  • -d is the delimiter (here using \ for a space)
  • -f is the field selector

Notice that there is a space after the \.



回答5:

-c is for characters, you want -f for fields, and -d to indicate your separator of space instead of the default tab:

cut -d " " -f 1 file


标签: bash file unix