Page cover

bash/csv_files

I love exporting results to .csv files because of all the commands that let you handle them so efficiently. Here are my essentials: πŸ“ŠπŸ’»

Printing CSV Columns

With the following command, you can select which columns to print from a CSV file. The -F',' option sets the comma as the delimiter, and {print $x} prints the column you specify by changing x to the desired column number.

Basic Command

awk -F'DELIMIER' '{print X}' FILENAME

Where:

  • DELIMITER: The character separating the columns (e.g., ',' for CSV).

  • X: The column number to print (e.g., $1 for the first column).

  • FILENAME: The name of the file to process.

Examples

To print the first column

awk -F',' '{print $1}' file.csv

To print the second and fourth columns:

awk -F',' '{print $2, $4}' file.csv

Filtering CSV Rows

With the following command, you can filter rows based on specific conditions. The awk command allows you to set a condition to only print lines that match your criteria.

Basic Command

Where:

  • CONDITION: The condition you want to use for filtering (e.g., $x == "value" to match the "x" column to a value).

  • FILENAME: The name of the file to process.

Examples

To filter rows where the value in the third column is "failed":

To filter rows where the value in the second column is not "failed":

To filter rows where the value in the second column is "active" and the value in the third column is not "failed":

Combining Printing and Filtering

You can combine printing and filtering conditions in a single awk command, while also specifying the delimiter

Basic Command

Examples

To filter rows where the value in the second column is "active" and the value in the third column is not "failed", and then print the first column:

Last updated