Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...