Writing onto a CSV column on applescript - csv
So I'm creating a script in AppleScript that needs to write onto a column in a CSV. I've already read from the CSV and I have code on how to write onto a CSV but it doesn't write at all. I want to write on column 22. At the moment, I can read from that column but I'm not sure how to edit the column. Or is there a way to edit a certain box in excel like A3 to say this "Yes". I've attached my code below.
set theFile to (choose file)
set f to read theFile
-- break the file into paragraphs (c.f. rows)
repeat with row in (paragraphs of f)
-- parse the row into comma-delimited fields
set fields to parseCSV(row as text)
-- now you have your data:
set verifyAccountStatus to item 22 of fields
set theResult to writeTo(verifyAccountStatus, "Yes", text, true)
end repeat
on parseCSV(theText)
set {od, my text item delimiters} to {my text item delimiters, ","}
set parsedText to text items of theText
set my text item delimiters to od
return parsedText
end parseCSV
on writeTo(targetFile, theData, dataType, apendData)
-- targetFile is the path to the file you want to write
-- theData is the data you want in the file.
-- dataType is the data type of theData and it can be text, list, record etc.
-- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
try
set openFile to open for access file targetFile with write permission
if apendData is false then set eof of openFile to 0
write theData to openFile starting at eof as dataType
close access openFile
return true
on error
try
close access file targetFile
end try
return false
end try
end writeTo
EDIT:
For some reason it isn't working when I run this.
set theFile to (choose file)
set openFile to open for access theFile with write permission
do shell script "awk -F, '$1 ~ /Line 7/{$22=\"hello\"} 1' openFile"
close access openFile
It says it can't open file openFile
Maybe consider doing this using awk which is built-in to OS X anyway. Say your file is called file.csv and it is comma-separated and looks like this:
Line 0,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,16
Line 1,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,44
Line 2,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,93
Line 3,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,96
Line 4,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,19
Line 5,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,77
Line 6,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,30
Line 7,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,30
Line 8,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,1
Line 9,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,96
If you run this awk script in the Terminal, it will change all the field22 entries to "Hello"
awk -F, '{$22="hello"}1' OFS=, file.csv
and give you this:
Line 0,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,hello,f23,f24,16
Line 1,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,hello,f23,f24,44
Line 2,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,hello,f23,f24,93
Line 3,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,hello,f23,f24,96
Line 4,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,hello,f23,f24,19
Line 5,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,hello,f23,f24,77
Line 6,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,hello,f23,f24,30
Line 7,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,hello,f23,f24,30
Line 8,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,hello,f23,f24,1
Line 9,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,hello,f23,f24,96
If you want that in a new file, just redirect the output like this:
awk -F, '{$22="hello"}1' OFS=, file.csv > newfile.csv
You can call this from Applescript using:
do shell script "awk -F, '{$22=\"hello\"} 1' file.csv > newFile.csv"
If you want the user to choose a file from a dialog window, then your filename will be in an Applescript variable - in your example it is called theFile. You will then need to convert this to a filename that the shell and awk understand, and quote it and pass it to the shell something like this:
do shell script "awk -F, '{$22=\"hello\"} 1' & quoted form of POSIX path of theFile & " > /tmp/a"
If you only want to change field 22 on lines that contain "77" anywhere on them, do this:
awk -F, '/77/ {$22="hello"} 1' file.csv
Line 0,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,16
Line 1,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,44
Line 2,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,93
Line 3,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,96
Line 4,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,19
Line 5 field2 field3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 f16 f17 f18 f19 f20 f21 hello f23 f24 77
Line 6,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,30
Line 7,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,30
Line 8,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,1
Line 9,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,96
If you only want to change field22 on lines where field 1 matches "Line 7", you can do this:
awk -F, '$1 ~ /Line 7/ {$22="hello"} 1' file.csv
Line 0,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,16
Line 1,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,44
Line 2,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,93
Line 3,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,96
Line 4,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,19
Line 5,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,77
Line 6,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,30
Line 7 field2 field3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 f16 f17 f18 f19 f20 f21 hello f23 f24 30
Line 8,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,1
Line 9,field2,field3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,96
Note:
The -F, just tells awk that input fields are separated by commas. The OFS=, tells awk to separate output fields by commas.
Related
CSV Column Insertion via awk
I am trying to insert a column in front of the first column in a comma separated value file (CSV). At first blush, awk seems to be the way to go but, I'm struggling with how to move down the new column. CSV File A,B,C,D,E,F 1,2,3,4,5,6 2,3,4,5,6,7 3,4,5,6,7,8 4,5,6,7,8,9 Attempted Code awk 'BEGIN{FS=OFS=","}{$1=$1 OFS (FNR<1 ? $1 "0\nA\n2\nC" : "col")}1' Result A,col,B,C,D,E,F 1,col,2,3,4,5,6 2,col,3,4,5,6,7 3,col,4,5,6,7,8 4,col,5,6,7,8,9 Expected Result col,A,B,C,D,E,F 0,1,2,3,4,5,6 A,2,3,4,5,6,7 2,3,4,5,6,7,8 C,4,5,6,7,8,9
This can be easily done using paste + printf: paste -d, <(printf "col\n0\nA\n2\nC\n") file col,A,B,C,D,E,F 0,1,2,3,4,5,6 A,2,3,4,5,6,7 2,3,4,5,6,7,8 C,4,5,6,7,8,9 <(...) is process substitution available in bash. For other shells use a pipeline like this: printf "col\n0\nA\n2\nC\n" | paste -d, - file
With awk only you could try following solution, written and tested with shown samples. awk -v value="$(echo -e "col\n0\nA\n2\nC")" ' BEGIN{ FS=OFS="," num=split(value,arr,ORS) for(i=1;i<=num;i++){ newVal[i]=arr[i] } } { $1=arr[FNR] OFS $1 } 1 ' Input_file Explanation: First of all creating awk variable named value whose value is echo(shell command)'s output. NOTE: using -e option with echo will make sure that \n aren't getting treated as literal characters. Then in BEGIN section of awk program, setting FS and OFS as , here for all line of Input_file. Using split function on value variable into array named arr with delimiter of ORS(new line). Then traversing through for loop till value of num(total values posted by echo command). Then creating array named newVal with index of i(1,2,3 and so on) and its value is array arr value. In main awk program, setting first field's value to array arr value and $1 and printing the line then.
Increment field value provided another field matches a string
I am trying to increment a value in a csv file, provided it matches a search string. Here is the script that was utilized: awk -i inplace -F',' '$1 == "FL" { print $1, $2+1} ' data.txt Contents of data.txt: NY,1 FL,5 CA,1 Current Output: FL 6 Intended Output: NY,1 FL,6 CA,1 Thanks.
$ awk 'BEGIN{FS=OFS=","} $1=="FL"{++$2} 1' data.txt NY,1 FL,6 CA,1
Intended Output: NY,1 FL,6 CA,1 I would harness GNU AWK for this task following way, let file.txt content be NY,1 FL,5 CA,1 then awk 'BEGIN{FS=OFS=",";ORS=" "}{print $1,$2+($1=="FL")}' file.txt gives output NY,1 FL,6 CA,1 Explanation: I inform GNU AWK that field separator (FS) and output field separator (OFS) is , and output row separator (ORS) is space with accordance to your requirements. Then for each line I print 1st field followed by 2nd field increased by is 1st field FL? with 1 denoting it does hold, 0 denotes it does not hold. If you want to know more about FS or OFS or ORS then read 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR (tested in gawk 4.2.1)
Use this Perl one-liner: perl -i -F',' -lane 'if ( $F[0] eq "FL" ) { $F[1]++; } print join ",", #F;' data.txt The Perl one-liner uses these command line flags: -e : Tells Perl to look for code in-line, instead of in a file. -n : Loop over the input one line at a time, assigning it to $_ by default. -l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing. -a : Split $_ into array #F on whitespace or on the regex specified in -F option. -F',' : Split into #F on comma, rather than on whitespace. -i.bak : Edit input files in-place (overwrite the input file). Before overwriting, save a backup copy of the original file by appending to its name the extension .bak. If you want to skip writing a backup file, just use -i and skip the extension. SEE ALSO: perldoc perlrun: how to execute the Perl interpreter: command line switches
transform multiline text into csv with awk sed and grep
I run a shell command that returns a list of repeated values like this (note the indentation): Name: vm346 cpu 1 (12%) 6150m (76%) memory 1130Mi (7%) 1130Mi (7%) Name: vm847 cpu 6 (75%) 30150m (376%) memory 12980Mi (87%) 12980Mi (87%) Name: vm848 cpu 3500m (43%) 17150m (214%) memory 6216Mi (41%) 6216Mi (41%) I am trying to transform that data like this (in csv): vm346,1,(12%),6150m,(76%),1130Mi,(7%),1130Mi,(7%) vm847,6,(75%),30150m,(376%),12980Mi,(87%),12980Mi,(87%) vm848,3500m,(43%),17150m,(214%),6216Mi,(41%),6216Mi,(41%) The problem is that any given dataset like the one above is always on more than one line. when I pipe that into it awk it drives me mad because even if I use: BEGIN{ FS="\n" } to try and stitch the data together in one line, it doesn't work. No matter what I do, awk keeps the name value as a separated line above everything else. I am sorry I haven't much code to share but I have been spinning my wheels with this for a few hours now and I am running out of ideas...
I can solve this in Perl: perl -ane 'print join ",", #F[1 .. $#F]; print $F[0] eq "memory" ? "\n" : ","' It should be easy to translate it to awk if you need it. How does it work? -a splits each line on whitespace into the #F array -n reads the input line by line and runs the code specified after -e for each line We print all the elements but the first one separated by commas (see join) We then look at the first column, if it's memory, we are at the last line of the block, so we print a newline, otherwise we print a comma
With AWK, one option is to set RS to "Name: ", and ignore the first record with NR > 1, e.g. awk -v RS="Name: " 'BEGIN{OFS=","} NR > 1 {print $1, $3, $4, $5, $6, $8, $9, $10, $11}' file #> vm346,1,(12%),6150m,(76%),1130Mi,(7%),1130Mi,(7%) #> vm847,6,(75%),30150m,(376%),12980Mi,(87%),12980Mi,(87%) #> vm848,3500m,(43%),17150m,(214%),6216Mi,(41%),6216Mi,(41%)
awk '{$1=""}1' | paste -sd' \n' - | awk '{$1=$1}1' OFS=, Get rid of the first column. Join every three rows. Same idea with sed: sed 's/^ *[^ ]* *//' | paste -sd' \n' - | sed 's/ */,/g' Something else: awk ' $1=="Name:" { sep=ors ors=ORS } { for (i=2;i<=NF;++i) { printf "%s%s",sep,$i sep=OFS } } END {printf "%s",ors}' Or if you want to print an ORS based on the first field being "memory" (note that this program may end without printing a terminating ORS): awk '{for (i=2;i<=NF;++i) printf "%s%s",$i,(i==NF && $1=="memory" ? ORS : OFS)}' something else else: awk -v OFS=, ' index($0,$1)==1 { OFS=ors ors=ORS } { $1="" printf "%s",$0 OFS=ofs } END {printf "%s",ors} BEGIN {ofs=OFS}'
This might work for you (GNU sed): sed -nE '/^ +\S+ +/{s///;H;$!d};x;/./s/\s+/,/gp;x;s/^\S+ +//;h' file In overview the sed program processes indented lines, already gathered lines (except in the case that the current line is the first line of the file) and non-indented lines. Turn off implicit printing and enable extended regexp's. (-nE). If the current line is indented, remove the indent, the first field and any following spaces, append the result to the hold space and if it is not the last line, delete it. Otherwise, check the hold space for gathered lines and if found, replace one or more whitespaces by commas and print the result. Then prep the current line by removing the first field and any following spaces and replace the hold space with the result. The solution seems logically back-to-front, but programming in this style avoids having to check for end-of-file multiple times and invoking labels and gotos. N.B. This solution will work for any number of indented lines.
Here is a ruby to do that: ruby -e ' s=$<.read s.scan(/^([^ \t]+:)([\s\S]+?)(?=^\1|\z)/m). # parse blocks map(&:last). # get data part # parse and join the data fields: map{|block| block.split(/\n[ \t]+[^ \t]+[ \t]+/)}. map{|lines| lines.map(&:strip).join(" ").split().join(",")}. each{|l| puts "#{l}"} ' file vm346,1,(12%),6150m,(76%),1130Mi,(7%),1130Mi,(7%) vm847,6,(75%),30150m,(376%),12980Mi,(87%),12980Mi,(87%) vm848,3500m,(43%),17150m,(214%),6216Mi,(41%),6216Mi,(41%) The advantage is that this is not dependent on the number of lines or the number of fields. It is parsing data that is in blocks of the form: START: ([ \t]+[data_with_no_space])*\n l1 ([ \t]+[data_with_no_space])*\n ... START: ... Works this way: Parse the blocks with THIS REGEX; Save an array of the data elements; Join the sub arrays and then split into data fields; Join(',') to make a csv.
Extract column data from csv file based on row values
I am trying to use awk/sed to extract specific column data based on row values. My actual files have 15 columns and over 1,000 rows (From a .csv file.) Simple EXAMPLE: Input; a cdv file with a total of 5 columns and 100 rows. Output; data from column 2 through 5 based on specific row values from column 2. (I have a specific list of the row values I want the operator to filter out. The values are numbers.) File looks like this: "Date","IdNo","Color","Height","Education" "06/02/16","7438","Red","54","4" "06/02/16","7439","Yellow","57","3" "06/03/16","7500","Red","55","3" Recently Tried in AWK: #!/usr/bin/awk -f #I need to extract a full line when column 2 has a specific 5 digit value awk '\ BEGIN { awk -F "," \ { if ( $2 == "19650" ) { \ {print $1 "," $6} \ } exit } chmod u+x PPMDfUN.AWK The operator response: /var/folders/1_/drk_nwld48bb0vfvdm_d9n0h0000gq/T/PPMDfUN- 489939602.998.AWK.command ; exit; /usr/bin/awk: syntax error at source line 3 source file /private/var/folders/1_/drk_nwld48bb0vfvdm_d9n0h0000gq/T/PPMDfUN- 489939602.997.AWK context is awk >>> ' <<< /usr/bin/awk: bailing out at source line 17 logout Output Example: I want full row lines based if column 2 equals 7439 & 7500. “Date","IdNo","Color","Height","Education" "06/02/16","7439","Yellow","57","3" "06/03/16","7500","Red","55","3"
here you go... $ awk -F, -v q='"' '$2==q"7439"q' file "06/02/16","7439","Yellow","57","3" There is not much to explain, other than convenience variable q defined for double quotes helps to eliminate escaping.
awk -F, 'NR<2;$2~/7439|7500/' file "Date","IdNo","Color","Height","Education" "06/02/16","7439","Yellow","57","3" "06/03/16","7500","Red","55","3"
Pasting Text Vertically Into .CSV File
I have this awk script to write a text file to a specific cell in a .cvs file, but I am trying to have the text displayed vertically, not horizontally. `nawk -v r=2 -v c=3 ' BEGIN { FS=OFS="," } FNR == NR { val = sprintf("%s%s%s", val, NR > 1 ? " " : "", $0) next } FNR == r { $c = val } 1' file new_one.csv` Want the text like this
Can't you do something like: val = sprintf("%s%s%s", val, NR > 1 ? " " : "", $0) + '\n' Documentation here
Assuming a csv input file like: a,b,c d,e,f g,h,i k,l,m and the data you want vertically like: This file has words horizontally here's one way to modify your script: NR==FNR {gsub(" ","\n"); val="\""$0"\""; next} This is going to replace all the single spaces in $0 with newlines. Then the whole line is assigned to val, but wrapped in double quotes per wikipedia's csv page. Running this with the data files I created from the command line (using a slightly different syntax used than you for FS/OFS): awk -F"," -v r=2 -v c=3 'NR==FNR{gsub(" ","\n"); val="\""$0"\""; next} FNR==r {$c=val} 1' OFS="," vert data a,b,c d,e,"This file has words horizontally" g,h,i k,l,m where vert is the name of the vertical data and data is the name of the csv data file. Notice that f at [2,3] has been replaced with the altered input from the vert file. Be aware that the row/column indexing you've chosen only works if none of the fields in the data file have internal commas in them and that awk isn't going to be your best friend for parsing csv files in general.