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