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"
4
  • What about using xxd? Commented May 9, 2023 at 6: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. Commented May 9, 2023 at 7:07
  • Your question is in fact not related to files at all. line is a string, so use string processing functions. Commented May 9, 2023 at 7:07
  • for (( i = 0; i < ${#line}; i++ )); do convertnum "${line:i:1}"; done Commented May 9, 2023 at 7:08

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

3 Comments

The first comment you have, the {var} is used so the default 0 is not. Also just in case convert consumes stdin fd 0
Have a look at {varname} under redirecion , LESS='+/^REDIRECTION' man bash
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.