使用 bash (sed/awk) 提取 CSV 文件中的行和列? [英] using bash (sed/awk) to extract rows AND columns in CSV files?

查看:31
本文介绍了使用 bash (sed/awk) 提取 CSV 文件中的行和列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bash 是否能够处理从 csv 文件中提取行和列?希望我不必求助于python..

Is bash capable of handling extracting rows and columns from csv files? Hoping I don't have to resort to python..

我的 5 列 csv 文件如下所示:

My 5-column csv file looks like:

Rank,Name,School,Major,Year
1,John,Harvard,Computer Science,3
2,Bill,Yale,Political Science,4
3,Mark,Stanford,Biology,1
4,Jane,Princeton,Electrical Engineering,3
5,Alex,MIT,Management Economics,2

我只想提取第 3、4、5 列的内容,忽略第一行,所以输出如下:

I only want to extract the 3rd, 4th, and 5th column contents, ignoring the first row, so output looks like:

Harvard,Computer Science,3
Yale,Political Science,4
Stanford,Biology,1
Princeton,Electrical Engineering,3
MIT,Management Economics,2

到目前为止,我只能让 awk 打印出我的 CSV 文件的每一行或每一列,而不是像这种情况下的特定列/行!bash 能做到这一点吗?

So far I can only get awk to print out either each row, or each column of my CSV file, but not specific cols/rows like this case! Can bash do this?

推荐答案

Bash 解决方案;

使用 IFS

#!/bin/bash
while IFS=',' read -r rank name school major year; do
    echo -e "Rank	: $rank
Name	: $name
School	: $school
Major	: $major
Year	: $year
"
done < file.csv
IFS=$' 	
'

使用字符串操作和数组

#!/bin/bash
declare -a arr
while read -r line; do
    arr=(${line//,/ })
    printf "Rank	: %s
Name	: %s
School	: %s
Major	: %s
Year	: %s
" ${arr[@]}
done < file.csv

这篇关于使用 bash (sed/awk) 提取 CSV 文件中的行和列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆