How to copy the head of files into some other files without losing linebreaks in bash?

StackOverflow https://stackoverflow.com/questions/22435513

  •  15-06-2023
  •  | 
  •  

سؤال

What I've got is something like this:

working_dir
|-- samples
|-- table1.tbl
|-- table2.tbl
|-- table3.tbl

What I want to have is something like this:

working_dir
|-- samples
|   |-- table1.tbl
|   |-- table2.tbl
|   |-- table3.tbl
|-- table1.tbl
|-- table2.tbl
|-- table3.tbl

And the .tbl files in the samples directory will contain the first 10 lines of those .tbl files in the root directory.

I've tried

for FILE in `ls *.tbl`; do
  NEWFILE="samples/$FILE"
  if [ ! -f "$NEWFILE" ] ; then
      touch "$NEWFILE"
  fi
  echo `head $FILE` > $NEWFILE
done

but the linebreaks in the .tbl files under samples were lost, the content of the 10 lines are squeezed into one line in each .tbl file.

Any help? Thanks.

هل كانت مفيدة؟

المحلول

for FILE in *.tbl; do
  head "$FILE" > "samples/$FILE"
done

Your problem was caused by the echo and the backticks. The backticks flatten the output into one line and echo simply outputs that single line.

نصائح أخرى

You can try this one:

#!/bin/bash

LIST=/path/to/file
find /absolute/path/to/dir -name "*.tbl" > /path/to/file

for FILE in $(cat /path/to/file); do
    head "$FILE" > "/path/to/sample/$FILE"
done
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top