Add the filename to a csv column in linux

January 26, 2011 at 08:58:45
Specs: linux
I have a script that adds the file name of csv file to the last column of the csv file with the column header of ID. I found a script on this site. (Acknowlegde Mechanix2Go)

@echo off
setLocal EnableDelayedExpansion

for /f "tokens=* delims= " %%c in ('dir/b/a-d *.csv') do (
set FN=%%~Nc
set /a N=0

for /f "tokens=* delims= " %%a in (%%c) do (
set /a N+=1
if !N! equ 1 (
echo %%a, id > !FN!.csv
) else (
echo %%a, !FN! >> !FN!.csv
)
)
)

Unfortunalty it does not port to linux. I am hoping someone knows how to do this in either bash script.

Thanks


See More: Add the filename to a csv column in linux

Report •


#1
January 26, 2011 at 10:02:37
I don't know Batch, but I speak fluent bash. Explain further what you want, with maybe a data example, and I'll see what I can do.

Report •

#2
January 26, 2011 at 10:15:41
Unfortunately I speak Batch but not Bash. You could try.

https://bbs.archlinux.org/viewtopic...


Report •

#3
January 26, 2011 at 16:56:57
for file in *.csv
do
    gawk -F"," '{$NF=","FILENAME}1' $file  > t && mv t $file
done

GNU win32 packages | Gawk


Report •

Related Solutions

#4
January 26, 2011 at 19:06:30
Hi all,
Ghostdog, your bash script had an error of:
"gawk: cmd. line:1: fatal: cannot open file `file' for reading (No such file or directory"

The batch file does the following:
I have multicsv files of different amount of colums. I need to add the file name of each csv file to the last colum under the header of id.
IE
Filename bob123.csv
column1,column2,column3
data1,data2,data3

would become
Filename bob123.csv
column1,column2,column3,id
data1,data2,data3,bob123.csv

The batch file does the job, but i would like to use it on a linux system.


Report •

#5
January 26, 2011 at 19:42:27
to use a variable in linux, prefix the variable name with $. I have amended the script I wrote. Please go get yourself acquainted with linux shell scripting before you go any further.

GNU win32 packages | Gawk


Report •


Ask Question