tmpfile=$( mktemp )
for pathname in /path/to/dir/*.csv; do
head -n 1 "$pathname" >"$tmpfile"
cat "$tmpfile >"$pathname"
done
rm "$tmpfile"
That is, extract the header using head -n 1
to a temporary file (assuming it's the first line only), then truncate the original file and insert the header from the temporary file.
If the header is exactly identical in all files:
tmpfile=$( mktemp )
set -- /path/to/dir/*.csv
head -n 1 "$1" >"$tmpfile"
for pathname do
cat "$tmpfile" >"$pathname"
done
rm "$tmpfile"
This first sets the positional parameters to the list of files that we're interested in, then extracts the header from the first of them. The loop iterates over the positional parameters (the CSV files) and truncates each, inserting the header.
In both examples above, the pattern /path/to/dir/*.csv
is assumed to match all affected files. A real world example of an actual pattern may be
/var/log/myprogram/dir1/*.csv /var/log/myprogram/dir2/*.csv
or, if you're using a shell that understands brace expansion:
/var/log/myprogram/{dir1,dir2}/*.csv