Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

csv - Adding column of filename to all the files in a directory

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,

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.

I tried:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
awk '
BEGIN { FS=OFS=", " }
FNR == 1 {
    fname = FILENAME
    out = "mod" FILENAME
    sub(/.csv$/,"",1,fname)
    print "filename", $0 > out
    next
}
{ print fname, $0 > out }
' *.csv

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...