In this blog we are going to study How to read file word by word using bash shell script in Linux or Unix based system. This program may be useful when we need to process each word of a file.

Sample for How to read file word by word using bash shell script

How to use above code:

  • Save the sample code as sample.sh
  • Make the sample script executable byUbuntu@ubuntu-desk-ubuntu:~$ chmod +x sample.sh
  • Run the script Ubuntu@ubuntu-desk-ubuntu:~$ sh sample.sh

How to Read File word by word using bash shell script

How it works

  • IFS is predefined shell environment shell variable known as internal filed separator.
  • Its default value is <space> , <tab> or <new line>
  • We can print IFS value by echo $IFS commnad on Linux terminal.
  • In our shell script we have saved its default value in variable old. ( old=$IFS )
  • Through export IFS=” “ , we have changed IFS value to <space>
  • read file command would ask name of your file to be processed.
  • Because we have changed IFS value to <space> , so whenever a <space> is found in a file’s content it will be treated as newline. Hence following script will print each word line by line

  • At the end we restore the IFS value by IFS=$old

Ref:

http://wikistack.com/internal-field-separator-shell-script/

https://unix.stackexchange.com/questions/195224/read-file-word-by-word