TurtleMan TurtleMan - 1 year ago 87
Linux Question

How to read in a line in a bash script using IFS and while the line is being read create a new line between a specified charater

I am trying to create a bash script that will read in a file that has one line and as it is reading the line and encounters whitespace create a new line then continue reading the line

File trying to read

david:69 jim:98 peter:21 sam:56 april:32

This is my current bash script


fileName=$1 # storing the file
numberSpaces=$2 # will be used later to specify the number of spaces inbetween name:score

# Checking if no file was specified on the command line
[ $# -eq 0 ] && { echo "No file specified"; exit 1;}

# Checking if the file entered on the command line exists
[ ! -f $fileName ] && { echo "File $fileName not found."; exit 2;}

# Internal Field Seperator(IFS) will read what is on the left and right of a specified char
while IFS=' ' read -r name;
echo "$name"
echo -e "\n"
done < $fileName

#while read -r line
# name="$line"
# echo "Content of file - $name"
#done < "$fileName"

I am trying to get it to print to the screen

$ spacing.sh file.txt
$ david:69
$ jim:98
$ peter:21
$ sam:56
$ april:32

It is currently just printing the file contents on one line.
Any help or suggestion would be greatly appreciated

Answer Source

In one line:

tr -s " " "\n" < file.txt
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download