TurtleMan TurtleMan - 2 months ago 8
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

#!/bin/bash

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;
do
echo "$name"
echo -e "\n"
done < $fileName

#while read -r line
#do
# 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

In one line:

tr -s " " "\n" < file.txt
Comments