file validation in linux scripting

If you want to do it in pure bash, use the following script:

#!/bin/bash
while read line; do
  line=( ${line//[:]/ } )
  for i in "${!line[@]}"; do
    [ ! -z "${line[$i]##*[!0-9]*}" ] && printf "integer" || printf "string"
    [ "$i" -ne $(( ${#line[@]} - 1)) ] && printf ":" || echo
  done
done < $1

Pass your file as first argument.

This script iterates over all lines in file (while read line; do ... done < $1, where $1 is the file path), then it replaces all colons in each line with spaces (${line//[:]/ }). A variable with values separated with spaces can be treated as an array, and that’s why this substitution is in brackets.

Now we can iterate over all values in a line. For each index in the line array we:

  1. Check if it contains digits only. It is done by removing all digits from current value in line (${line[$i]##*[!0-9]*}, where line[$i] is the current value) and then checking if it’s empty (! -z). If it is, then we print integer, or otherwise string.
  2. Check if this is not the last element in array. It is done by comparing current index ($i) with the array length (${#line[@]}) decreased by 1. If current index is not the last, we print :. Otherwise, we print new line.

This is done for all lines in a given file. Given an input file with the following content:

col1:col2:col3:col4
1:word:2:word2
word3:3:word4:4

We get the following result:

string:string:string:string
integer:string:integer:string
string:integer:string:integer

Leave a Comment