0

Can anyone let me know how to read a binary file for some data and write that data to the new binary file in shell script and so on? I am using Linux.

Note: cat file1 > file2 : not required as this writes the complete data.

Requirement: reading some data and writing and reading again and writing..

while read -n1 ch
do
cat $ch > $output   # Tried this, showing error. While writing the data after reading, cat command throws error : No such file or directory.

done < $filename

terdon
  • 242,166
  • What is ch? Is it a file name? Are you just looking for printf '%s\n' "$ch" >> "$output"? – terdon Jul 08 '21 at 13:31
  • 2
    What do you mean by "binary data"? Bash read is intended for line-based text. It skips NUL characters completely, and it returns an empty string for newline regardless of the IFS value (although -N1 does return actual newlines). printf won't output NULL either. So your binary file will be mangled. Also, using > file in a loop just rewrites the file per character, and >> file opens and closes the file for each char. Use > file outside the loop (after the done). – Paul_Pedant Jul 08 '21 at 14:50

1 Answers1

0

cat is a command used to concatenate files and, by extension, also used to print the contents of a single file to standard output. All cat does is take a file or whatever is fed into its standard input stream and print it out. You It doesn't print its arguments, like echo or a print statement in other languages, that isn't what it's for.

So you're using the wrong tool for the job here. You want echo which prints out whatever you give it adding a newline at the end (usually, and by default) or, better and safer especially for binary data, printf:

while read -r -n1 ch
do
    printf '%s\n' "$ch" >> "$output"
done < "$filename"

Note the -r which tells read not to interpret backslashes as escapes, the use of >> instead of > since with > you would be overwriting $output on each iteration and would only ever see the last character read and the use of quotes around your variables to protect them from split+glob expansion by the shell.

terdon
  • 242,166