0

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"
Dave Shah
  • 91
  • 6
  • What about using `xxd`? – Jardel Lucca May 09 '23 at 06:11
  • It's not obvious whether the duplicate actually answers your question because it's not clear what exactly you want. If `convertnum` is just a simple replacement function, you don't really need to access the entire file at once. If you need access to all the previous and subsequent lines, you can similarly read the entire file into an array. – tripleee May 09 '23 at 07:07
  • Your question is in fact not related to files at all. `line` is a string, so use string processing functions. – Yves Daoust May 09 '23 at 07:07
  • `for (( i = 0; i < ${#line}; i++ )); do convertnum "${line:i:1}"; done` – Renaud Pacalet May 09 '23 at 07:08

2 Answers2

1

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"
0

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:]' '\0' < "$file1")

  • Remove the echo to actually run convertnum against each char.
Jetchisel
  • 7,493
  • 2
  • 19
  • 18