Home > database >  How to loop through each word in a line of a file?
How to loop through each word in a line of a file?

Time:12-17

The content of text.txt is:

absolute abstract academic accepted accident 

I'm trying to loop through each word and print it so I can get an output like this:

absolute
abstract
academic
accepted
accident

I tried using cat but it starts from the field 1 so it end up ignoring a word

words="$(cat text.txt | wc -w)"

for ((i=0; i<$words; i  )); do

        cut -d' ' -f$i text.txt

done

I think awk could also be useful but I don't know very well its syntax.

awk '{print $'$i'}'   

I tried something like this but the output was a mess.

CodePudding user response:

A simple way without loop:

$ tr ' ' $'\n' < file
absolute
abstract
academic
accepted
accident

or using printf:

printf '%s\n' $(<file)

CodePudding user response:

This might work for you (GNU grep & sed):

grep -o '\S\ ' file

or:

sed -n 's/\>\s*/\n/;P;D' file

CodePudding user response:

You over-complicate it, bash for loop can go through a list of words:

for word in $(cat text.txt); do
  echo "$word"
done

CodePudding user response:

You might use GNU AWK following way, let file.txt content be

absolute abstract academic accepted accident

then

awk 'BEGIN{RS="[[:space:]] "}{print}' file.txt

gives output

absolute
abstract
academic
accepted
accident

Explanation: I inform GNU AWK that row are separated by one-or-more ( ) whitespace characters, then each row is printed using default output row separator, which is newline character.

(tested in GNU Awk 5.0.1)

If you prefer GNU sed then you might simply do

sed 'y/ /\n/' file.txt

where sole command given mean replace each space using newline character, output is same as above

(tested in GNU sed 4.7)

CodePudding user response:

$ xargs -n 1 echo < text.txt
absolute
abstract
academic
accepted
accident

or with any awk:

$ awk '{for (i=1; i<=NF; i  ) print $i}' text.txt
absolute
abstract
academic
accepted
accident
  • Related