Hello everyone
I’ve just started using Bash; I’m working on my first piece of code. I’m reading a file where each line contains a number, and I need to validate those numbers and then display them. What
input="./numbers.txt"
function validation_line()
{ lines=$1 }
while IFS= read -r line; do
validation_line "$line"
done < "$input"
My question is: after reading each line of the file, I have to check the line; how can I read the value character by character?
It’s not the wrong thread, it’s basically the wrong forum.
This is Manjaro distribution forum, about Manjaro.
Your question is about general Linux question so it doesn’t really fit the Manjaro support forum.
Your questions would probably be answered in seconds by some random AI agent. Try ChatGPT for basic stuff like this. Copy your post to the AI it will answer.
You can do it a few ways, but the easiest is in bash is:
echo ${line,2,1}
# Starts at the 3rd character, but shows only 1
1st number: Position. It is zero indexed, so it starts at 0. (The example is the 3rd character.)
2nd number: Length. As you want 1 character, this will always be 1.
This shortcut or some of the others may not work for you. It depends.
You may likely have to do a for loop through the string.
#!/bin/bash
input="./numbers.txt"
function validation_line() {
lines=$1
for (( i=0; i<${#lines}; i++ )); do
char="${lines:i:1}"
# Deal with a character at a time here
echo "$char"
done
}
while IFS= read -r line; do
validation_line "$line"
done < "$input"
With #lines, the preceding pound/number-sgn is the bash shortcut for string length used in the for loop.