5

i have a CSV file i want to get the columns name for each column

sample :

image

how can i do that with awk or sed or grep ??

1
  • 1
    Please add your desired output for that sample input to your question.
    – Cyrus
    Jun 24, 2018 at 7:51

3 Answers 3

16
head -n 1 file.csv

or

sed 1q file.csv

or

grep -m 1 '' file.csv

or

awk 'NR==1 {print; exit}' file.csv
5
  • As print is the default action you can shorten the awk command to awk NR==1 file.csv.
    – dessert
    Jun 24, 2018 at 9:17
  • @dessert: Thank you. I'm aware of that. This way awk reads only the first line of the file.
    – Cyrus
    Jun 24, 2018 at 9:20
  • I don’t understand – awk 'NR==1 {print; exit}' does the exact same as awk NR==1.
    – dessert
    Jun 24, 2018 at 10:30
  • @dessert when awk NR==1, still awk will read your whole file's lines where those are not necessary to read. Also that can be only awk '{print; exit}' Jun 24, 2018 at 10:48
  • 1
    or awk '1;{exit}' Jun 24, 2018 at 11:09
3

You can use csvtool to obtain column names. First install it from Ubuntu repository:

apt install csvtool

Then run it on the csv file:

csvtool head 1 file.csv

Output:

name1,name2,name3

If You need each column name in a separate line use tr command like this:

csvtool head 1 file.csv | tr -s ',' '\n'

name1
name2
name3
2

While the answer for awk or sed or grep above is amazing, I would like to offer an alternative solution for those people who are not familiar with queries. You can use a Relational Database Management System (RDBMS) or some other tools, such as Acho, to process your CSVs.

How to upload a CSV and view the column name

  1. Upload your CSV using Add Resource

    You can choose CSV or MCSV to upload, just make sure that all the CSVs have the same data schema (same column name, column number, column data type) if you are using MCSV.

  2. CSV Preview

    After the file selection, you can use the CSV Preview mode to see all your column names and columns. Additionally, you can choose to turn on the Auto-detect Schema or the Safe Mode. Auto-detect Schema can automatically detect the CSV's column name and column types for you. If the 1st upload fails, try to upload it with the *Safe Mode on, which turns all the column data types into "string" for the CSV.

    If your CSV doesn't consist of any column name in the header row, just click Add a header row and edit those column names then. This way, your CSV will have the 1st row as its column name, which is super beneficial for your later data work.

  3. Add the CSV into a project and have the whole table

    After the CSV has been successfully uploaded, just add this CSV resource into a project for the data manipulation. Then open it in the project. You can easily see your CSV presented in a table with all its column names.

    CSV with all its column names

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .