I am trying to write a simple Bash loop to concatenate the first 10 bytes of all the files in a directory. So far, I have the code block:
for filename in /content/*.bin;
do
cat -- (`head --bytes 10 $filename`) > "file$i.combined"
done
However, the the syntax is clearly incorrect here. I know the inner command:
head --bytes 10 $filename
...returns what I need; the first 10 bytes of the passed filename. And when I use:
cat -- $filename > "file$i.combined"
...the code works, only it concats the entire file contents.
How can I combine the two functions so that my loop concatenates the first 10 bytes of all the looped files?
CodePudding user response:
The loop will do the concatenation for you (or rather, the output of the sequential executions of head
are written in order to the standard output of the loop itself); you don't need to use cat
.
for filename in /content/*.bin; do
head --bytes 10 "$filename"
done > "file$i.combined"
CodePudding user response:
With head
from GNU coreutils:
head -qc 10 /content/*.bin > combined
CodePudding user response:
You should use @chepner's answer, but to show how you could use cat
...
Here we have a recursive function that rolls everything up into a single copy of cat
.
catHeads() {
local first="$1"; shift || return
case $# in
0) head --bytes 10 "$first" ;;
1) cat <(head --bytes 10 "$first") <(head --bytes 10 "$1");;
*) cat <(head --bytes 10 "$first") <(catHeads "$@");;
esac
}
catHeads /content/*.bin >"file$i.combined"
Don't ever actually do this. Use chepner's answer (or Socowi's) instead.