开发者

Inserting filename into last column of csv file.

开发者 https://www.devze.com 2023-02-05 13:39 出处:网络
I would like to insert the file name of a CSV file into开发者_如何学JAVA the last column of the CSV file.

I would like to insert the file name of a CSV file into开发者_如何学JAVA the last column of the CSV file.

I found a successful windows batch file but I'm looking for a linux bash script.

I've enclosed the windows batch file:

@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
    )
  )
)

Looking forward to solving this one.

Henry


With (gnu)sed:

for file in *.csv; do
    sed -i "s/$/,$file/" "$file"
done

with POSIX sed:

for file in *.csv; do
    if sed "s/$/,$file/" "$file" > /tmp/"${file}".tmp; then
        mv /tmp/"${file}.tmp" "$file"
    fi
done


Simple.

import sys
import glob

for filename in glob.glob(sys.argv[1]):
    file = open(filename)
    data = [line.rstrip() + "," + filename for line in file]
    file.close()

    file = open(filename, "w")
    file.write("\n".join(data))
    file.close()

Save as "csvadd.py". Then this command will add the filename to the last column (replace test.csv ofcourse):

python csvadd.py test.csv

EDIT

Changed the code, it should now work with everything the OS supports (wildcards, etc). It will now also directly write the changes back to the file. USE WITH CAUTION

0

精彩评论

暂无评论...
验证码 换一张
取 消