How to Read File word by word using bash shell script
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
#!/bin/bash old=$IFS; export IFS=" " echo "Enter complete path of file to process" read file; for line in $(cat $file) do echo $line; done IFS=$old
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 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
for line in $(cat $file) do echo $line; done
- At the end we restore the IFS value by IFS=$old