Search code examples
bashloopsubuntunested-loops

How can I access every single character in a line in a given file


I'm trying to get every single character of every single line in a given file and then do convertnum() (Assume that the function works perfectly) on each single character. Here is what I have so far:

   #!/bin/bash
   file1=$1
   while read -r line
     do
        //I want to iterate over each "line" and then do convertnum "char" on every single character within the line but I don't know how to do it.
    done
   done < "$file1"

Solution

  • I believe the first answer is not quite right:

    • Because the default value of 0 for file descriptor (fd) will be used, the -u option is not required.
    • For reading null-delimited data, use the -d '' option. This option is unnecessary because you are working with a text file that contains newlines.
    • Although the -N1 option is used to read one character at a time, it does not guarantee that the characters are read line by line. As a result, you'll need to change the script to handle line-by-line processing.

    Here is the updated script:

    #!/usr/bin/env bash
    
    file1=$1
    
    while IFS= read -r line; do
      for (( i=0; i<${#line}; i++ )); do
        char="${line:$i:1}"
        echo $(convertnum "$char")
      done
    done < "$file1"