2

I have several thousands of files with coded weather information in a folder. To every file I need to add a header and footer with control characters. This is not the problem as I have the header and footer in separate files (achieved with the cat command in a bash script).

However, the modified files need to retain their original names - this gives me a problem as I only have a very basic scripting knowledge. The reason for keeping them is that these files will be parsed and decoded. The file names contain vital information for how the decoders will process the content.

All the files that are to be decoded are in a separate file, list_of_files_to_decode.txt.

A part of the folder content can look like this:

a_snvs02wiix170600_c_eswi_20121117062131_76.txt
a_smci40babj170600_c_kwbc_20121117061545_3.txt
a_sath40vtbb170600_c_ekmi_20121117061604_95.txt
a_usxx40mynn70600cca_c_edzw_20121117062020_34.txt
a_siin40dems170600_c_ojam_20121117062020_40.txt
a_smxx40fapr170600rra_c_lowm_20121117062604_67.txt    
list_of_files_to_decode.txt   
start-seq.txt    
stop-seq.txt  

I have checked the web, and tested some of my own ideas - using awk and sed - but I can't really find that any suitable way of how I can achieve this in an easy way. So, I would appreciate some help or hints of how to proceed.

4

3 回答 3

3
while IFS= read -r file; do
    cat header.txt "$file" footer.txt > newfile && mv newfile "$file"
done < list_of_files_to_decode.txt

解释

  • 我只是使用连接和 shell 重定向
  • &&是捷径。这与if condition; then action; fi
于 2012-11-17T14:40:23.170 回答
0

无环方式sed

OLDIFS=$IFS; IFS=$'\n'
sed -i '1 r header.txt
        1 N
        $ r footer.txt' $(<list_of_files_to_decode.txt)
IFS=$OLDIFS


笔记:

  • IFS仅在文件名中有空格时才设置为换行符
  • r在读取下一行时打印文件的内容
  • 1 N防止在内容之前打印第一行header.txt

    (细节:它读取第 2 行并附加到模式空间,触发r打印出 的内容header.txt。之后,现在由第 1 行和第 2 行组成的模式空间仅在循环结束时打印出来)

  • 当然,IFS如果您使用的是脚本,则可能不需要备份和重置。
于 2012-11-17T17:38:22.330 回答
0

唯一安全的方法是先重命名原始文件

mv $file $file.orig
cat header $file.orig footer > $file && rm $file.orig

反之亦然 创建一个新文件然后覆盖原始文件

cat header $file footer > $file.new && mv -f $file.new $file
于 2012-11-17T14:41:33.543 回答