Search code examples
bashechohead

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


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.


Solution

  • 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.