skip to Main Content

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"

2

Answers


  1. Maybe something like this:

    #!/usr/bin/env bash
    
    file1=$1
    
    while IFS= read -ru "$fd" -d '' -N1 char; do
      echo convertnum "$char"
    done {fd}< <(tr -s '[:space:]' '' < "$file1")
    

    • Remove the echo to actually run convertnum against each char.
    Login or Signup to reply.
  2. 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"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search