添加文件名的列的所有目录中的文件 [英] Adding column of filename to all the files in a directory

查看:90
本文介绍了添加文件名的列的所有目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目录的一套291 CSV 文件。我想要做的是一列追加到文件,其中列的内容是文件名的开始。因此,像:

I have a set of 291 csv files in a directory. What I want to do is to append a column to the start of the files, where the contents of that column is the filename. So like:

filename, ID, Mag, Magerr, RA, Decl, MJD, Blend
CSSJ235751.9+065855, 12302, 223, 34, 23.423, 23.54, 8723, 0,

其中,文件名是新的专栏中,我想补充。我想这一切我都在目录中的文件。我想使用 AWK SED 可能这一点,但我不是很熟悉他们。

where filename is the new column I would like to add. And I want to this to all the files i have in the directory. I was thinking of using awk or sed possibly for this, but I'm not very familiar with them.

我试过:

awk '{print "CSSJ235751.9+065855,"$0}' CSSJ235751.9+065855.csv > modCSSJ235751.9+065855.csv;

该工作之一。由我会怎么概括,所以我不能同时做所有的文件?

which worked for one. By how would I generalize so I can do all the files at once?

推荐答案

啧啧,追加到每行的开始只是很简单的sed的。

Gee, appending to the start of each line is just simple enough for sed.

for f in *.csv
do
    sed "1 s/^/filename,/; 2,$ s/^/${f%.*},/" f > f.new
    mv f f.old && mv f.new f
done

根据以上意见,文件名˚F被扩展为删除.csv扩展名。当你满意的你有你想要什么,你可以删除* .old的。同时,如果你陷入困境,可以还原原稿。

Per comments above, the filename f is expanded to remove the .csv extension. When you're satisfied you have what you want, you can delete *.old. Meanwhile, if you mess up, you can restore the originals.

这篇关于添加文件名的列的所有目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆