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
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
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
you can try
awk '{print $1}' your_file
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.
You can use:
cut -d\ -f1 file
Where:
\
for a space)Notice that there is a space
after the \
.
-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