NewB bash filtering/sorting q's.

Status
Not open for further replies.

armwt

Ars Legatus Legionis
18,229
Moderator
Got tired of doing this manually in excel, so thought I'd try doing it in bash for fun.

So I have a roughly 30K line .csv file. I need to strip out the 3rd column (already done using "csvfilter" and passing it to a new file).
Next I need to sort it alphabetically by the 1st column, done easily enough with "sort -k1 -t"

What I want to do next is a bit trickier, and I'm at a loss as to the best way to do it. Basically, I want to take the 1st few characters of "Column A", and when they change, add a blank line or otherwise create a separator.

Essentially, my file is a list of machine names, which follow a pattern where the 1st 4-5 characters are common to each office. I'm trying to divide my file up by office by sorting it, then separating it when the 1st characters change.

Thoughts?

If anyone has a simple way to do it in vbscript, that would work as well, but I'm really trying to force myself to use bash more and more so thus the exercise.
 

Drizzt321

Ars Legatus Legionis
34,946
Subscriptor++
Awk. Awk is awesome. Basically your awk program/script will iterate over each line, check the first few chars of the first column, if value has changed from the last line then you can have it output an extra newline '\n' (or if windows, carriage-return + newline '\r\n').

I _think_ this code is more or less correct, but I have done 0 testing so it probably has some bugs in it. But I think it'll illustrate (once you learn how to read awk ;)) what you need to do.

Code:
awk -F '<SEPARATOR CHAR>' "BEGIN { firstChars = '' } { current = substr($1,1,4); print (firstChars != current ? '\r\n' : ''); print $0, '\r\n' }"


GNU Awk Manual
 

armwt

Ars Legatus Legionis
18,229
Moderator
Youdaman!

That whole... "learning to read awk" is taking a while, but working on it! Still trying to tweak this to work just right, but looks like it is definitely on the right path.

Ex: Here's what my list looks like as an example:

ABC-DE-123 Adobe
ABC-DE-123 Microsoft
ABC-DE-123 Apple
ABC-DE-456 Adobe
ABC-DE-456 Microsoft
ABC-DE-456 Apple
FRG-DE-123 Adobe
FRG-DE-123 Microsoft
FRG-DE-123 Apple

Goal is to lump the "ABC-DE" entries together, and insert a blank line or other separator between. Reading in from "fileA" and outputting to "fileB". Then, I can run a vbscript against "fileB" relatively easily to lump those into separate tabs or files for distribution. I'd be a little tempted to do it all In vbscript except that a)vbscript makes FAR less sense to me, and b) so far, bash seems to be an order of magnitude faster on these types of things than Excel.

(Running all of this from a Mac, FWIW, although that shouldn't make much of a difference).
 

Drizzt321

Ars Legatus Legionis
34,946
Subscriptor++
Hm, yea, I must have a bug in the detection of switching between first parts. Try printing out the value of firstChars and current over enough data to see the switchover in order to try and track down why they aren't being considered equal.

Oh, wait, looks like I'm never setting the value of firstChars, so that's weird. So it should be printing out '\r\n' after every line of text. Strange. The substr() might not be working.

Ok, something else wrong, fixed it:

Code:
awk -F '<SEPARATOR CHAR>' 'BEGIN { firstChars = ""}{ current = substr($1,1,10); if(firstChars != "" && firstChars != current) print ""; firstChars = current;} {print $0 }' <INPUT FILE NAME>

Or, a VERY cool feature I just found! You can have AWK output to separate files based on the prefix name:

Code:
awk -F '<SEPARATOR CHAR>' '{ current = substr($1,1,10); print $2 > current }' <INPUT FILE NAME>

So based on your above small sample, you'd have the following files in the current working directory:

ABC-DE-123
ABC-DE-456
FRG-DE-123

So essentially you don't even need to do a sort on the original input, although the output files individually don't have a sorted list of software. You also don't need to do any csvfilter, you just output which columns you actually want using awk.


If you want to use your existing sort command, you can pipe the output of that directly into AWK if you want.

So:

Code:
sort <FILENAME> | awk -F ... > output_file.txt

Unix tools are intended to be piped together to build up more complex behavior for smaller, focused applications. Read the man page for sort, there's various ways to control the sorting. If you need to anyways.
 

armwt

Ars Legatus Legionis
18,229
Moderator
Thanks again. Already using pipe to chain things together, although being able to cut a step out with the sorting definitely makes a difference.

Quick question just to make sure I'm understanding your syntax: "<SEPARATOR CHAR>" - is this the character/pattern *after* the string we're sorting? (i.e. - the "DE" in the example?). Just trying to make sure I'm following and not going down blindly in the wrong direction.
 

Drizzt321

Ars Legatus Legionis
34,946
Subscriptor++
No, that's the character to separate fields. So if you have single space between fields (in the copy & paste of the sample data from the forum that's what it is) you'd use ' ', if it's a tab you'd use '\t'.

So what awk does, is it takes a line of text, and then it separates it out into fields. It uses a default, or what you pass it. You then operate/parse based on those fields using auto-generated/injected variables. $0 is the original line (including the newline char(s)), $1 is the first field, $2 is the second, etc. All the way up to $N being the number of fields (1-based).

So using:

Code:
awk -F ' ' 'BEGIN { firstChars = ""}{ current = substr($1,1,10); if(firstChars != "" && firstChars != current) print ""; firstChars = current;} {print $0 }' <INPUT FILE NAME>

with data looking like (note the single space between the first and 2nd fields):

Code:
ABC-DE-123 Adobe
ABC-DE-123 Microsoft
ABC-DE-123 Apple
ABC-DE-456 Adobe
ABC-DE-456 Microsoft
ABC-DE-456 Apple
FRG-DE-123 Adobe
FRG-DE-123 Microsoft
FRG-DE-123 Apple

The first line it sees the fields (assuming windows line endings, not unix):

Code:
$0: ABC-DE-123 Microsoft\r\n
$1: ABC-DE-123
$2: Microsoft
 

Drizzt321

Ars Legatus Legionis
34,946
Subscriptor++
You're welcome!

Now go forth and enjoy Unix tools! Seriously, they offer a fantastic way to do lots of things on files to process, parse, mangle, and generate other files from them.

Also take a look at the 2nd form I do, if you need to split the OS out into separate files per field 1, it does it based off of the field name for each one. Now since I'm a Unix guy I didn't bother with a file extension, but should be possible to add a ".csv" onto the end of the filenames.

Also, man pages (manual pages). They should be your first line of documentation for any Unix tool, with Google being your second usually great tool for finding documentation/help on tasks.
 

armwt

Ars Legatus Legionis
18,229
Moderator
Thanks again.

As a Mac admin, it bugs me that I'm not better in the Unix realm, but that's what I get for coming to the modern Mac ecosystem from old-school classic Mac OS and Amiga instead of from the Unix and/or developer/programmer side. I think it falls into the category of "I know what I know", but there are certainly a lot of gaps, and awk is one of those that I've always sort of known was out there, but never dove into in depth... but I figured that if I needed to figure out a task, and had a choice between vbscript or native unix tools... not a tough call at all from my end.
 
Status
Not open for further replies.