how read all bytes file without one end bytes

andrian

Active Member

Reaction score: 7
Messages: 153

Hi, how i can read all bytes from file without one end bytes?
In linux present this option "-c-1" in command "head" for example:
head -c-1 ./file.txt
How do i do this in FreeBSD?
 

im

Member

Reaction score: 18
Messages: 54

I tried to write a script that fixes it.
Make a file executable, run it with source filename as a single param.

./head-1.sh
Code:
#!/bin/sh
filename=$1
#filename="filename"
size=`stat -f %z ${filename}`
#echo ${size}
size1=$((${size}-1))
#echo ${size1}
head -c ${size1} ${filename}


I have a test file named as "test". The file includes "123456789" without LF character 0x0A.
# hd test
00000000 31 32 33 34 35 36 37 38 39 |123456789|
00000009
# cat test
123456789
# ./head-1.sh test
12345678

You can use dd instead of head, in case of parsing binary files.

Вітаю Львів!
 

memreflect

Active Member

Reaction score: 157
Messages: 177

Untested, but pretty sure it will work for you:
Code:
test $# -eq 0 && set -- -
for f in "$@"; do
    tmp="$(mktemp -t "")"
    cat -- "$f" > "$tmp"
    size=$(wc -c < "$tmp" | tr -d ' ')
    head -c $(("$size" - 1)) "$tmp"
    rm -f "$tmp"
done

To facilitate working with streaming input like FIFOs and program output piped into the standard input stream the way head(1) would, a temporary file is created and used. You can use this in combination with getopts (see sh(1)) to create your own replacement for head(1) that recreates at least some of the same behaviors that you're used to.

Or you can just install the sysutils/coreutils port/pkg and use ghead(1) (GNU head) like you would in Linux. :)
 
OP
andrian

andrian

Active Member

Reaction score: 7
Messages: 153

Found an easy way:
truncate -s-1 ./file.txt
Solved. Thank all.
 
  • Thanks
Reactions: im

SirDice

Administrator
Staff member
Administrator
Moderator

Reaction score: 10,164
Messages: 35,668

Realize that this actually truncates the file itself.
 
Top