Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

bash - file validation in linux scripting

I have a file, where first column contains header (file Id, value1_id, value1_type, value2_id, value2_type). file Id contains file names and value_id contains file value and value_type contains data type. I need to pick each file and check for the dataype and see if correct datatype values are entered in value_id. I could have done in Python but it is required in Linux, and I tried below script but its not that what is needed

while IFS=':' read col1, col2,col3,col4
do
echo 'col1'|grep "^[0-9]*$"
val="$?"

if [[$val==0]]
then
echo "Integer"
exit
fi

echo $col2|grep "^[a-zA-Z]*$"
val="$?"

if [[ $val==0]]
then
echo "String"
exit
fi
done < /root/file.ext

Can anyone help with this, I'm very much unaware of linux scripting.

question from:https://stackoverflow.com/questions/65887105/file-validation-in-linux-scripting

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...