Read user-defined file character by character in bash

I have a file that is unformatted, I want to put a new line after every 100th character and delete any other new lines so that the file looks with a constant width and readable

This piece of code helps to read all the lines.

 while read LINE
        do
                len=${#LINE}
                echo "Line length is : $len"
        done < $file

but how to do the same for characters

The idea should have something like this: (just an example, it may have syntax errors, not yet implemented)

 while read ch  #read character
  do
         chcount++ # increment character count

    if [ "$chcount" -eq "100" && "$ch"!="\n" ] #if 100th character and is not a new line
    then
        echo -e "\n" #echo new line
    elif [ "$ch"=="\n" ]  #if character is not 100th but new line
        then
        ch=" " $replace it with space
     fi
  done < $file

I study bash, so please go calmly!

+3
source share
4 answers

bashadds a flag -nto the standard command readto indicate the number of characters read, rather than a complete line:

while read -n1 c; do
    echo "$c"
done < $file
+4
source

100- ,

script, , .

. :

tr -d '\n' < inputfile | fold -w 100

.

+5

:

line_length=100
wrap $line_length <<< "$string"
wrap $line_length < file_name
wrap $line_length < <(command)
command | wrap $line_length

( , ), ( ). , . . , , , . , , . , .

wrap () { 
    local remainder rest part out_buffer line len=$1
    while IFS= read -r line
    do
        line="$remainder$line "
        (( part = $len - ${#out_buffer} ))
        out_buffer+=${line::$part}
        remainder=${line:$part}
        if (( ${#out_buffer} >= $len ))
        then
            printf '%s\n' "$out_buffer"
            out_buffer=
        fi
    done
    rest=$remainder
    while [[ $rest ]]
    do
        wrap $len <<< "$rest"
    done
    if [[ $out_buffer ]]
    then
        printf '%s\n' "$out_buffer"
        out_buffer=
    fi
}
+3
#!/bin/bash
w=~/testFile.txt
chcount=0
while read -r word ; do
        len=${#word}
        for (( i = 0 ; i <= $len - 1 ; ++i )) ; do
                let chcount+=1
                if [ $chcount -eq 100 ] ; then
                        printf "\n${word:$i:1}"
                        let chcount=0
                else
                        printf "${word:$i:1}"
                fi
        done
done < $w

Are you looking for something like this?

0
source

All Articles