如何编写一个bash
脚本,通过选择电子表格中csv
格式正确的列来创建列表?
如果我有csv
包含以下内容的文件:
[user]$ cat list1.csv
Last, First, user
lname1, fname1, user1
lname2, fname2, user2
[user]$ cat list2.csv
Last, First, user
lname3, fname3, user3
lname4, fname4, user4
我希望脚本被调用为CreateList <column> <file1> <file2> ...
例如 :
[user]$ CreateList 2 list2.csv list1.csv
list2: fname3, fname4
list1: fname1, fname2
答案1
这sh
不是bash
,但bash
可以运行它。
$ cat CreateList
#!/bin/sh
col="$1"; shift
for file
do
echo -n "$file:"
cut -d, -f"$col" "$file" | sed 1d | tr '\n' ','| sed '$ s/,$//'
echo
done
$
$ head -9 list*.csv
==> list1.csv <==
Last,First,user
lname1,fname1,user1
lname2,fname2,user2
==> list2.csv <==
Last,First,user
lname3,fname3,user3
lname4,fname4,user4
$
$ sh CreateList 2 list2.csv list1.csv
list2.csv:fname3,fname4
list1.csv:fname1,fname2
$
答案2
只需适当地调用 awk
# print first column:
cat list1.csv | awk '{ORS="\t"} {print $1}'
或者作为完整的脚本:
#!/bin/bash
column=$1
shift;
for item in "$@" ; do
#process item
echo "Processing $item:"
cat $item | awk '{ORS="\t"} {print "'"$column"'"}'
done
有帮助:
https://stackoverflow.com/questions/2021982/awk-without-printing-newline https://stackoverflow.com/questions/19075671/how-to-use-shell-variables-in-awk-script
答案3
也许不是最优雅的解决方案,但这将提供您指定的确切输出,包括空格:
#!/bin/bash
function CreateList()
{
col="$1"
shift
cut -d ',' -f $col $@ | sed -r '1d ; s/^[ ]+|[ ]$// ; y/\n/ /; s/[ ]+$/\n/' | xargs echo | sed 's/ /, /'
}
for f in list2.csv list1.csv
do
echo -n "${f//.csv}: "
CreateList 2 "$f"
done
输出:
list2: fname3, fname4
list1: fname1, fname2
答案4
简单的bash
:
#!/bin/bash
clm=$(($1 - 1))
shift
for file
do
printf "%s: " "$file"
unset res
{
read
while IFS=,\ read -a line
do
res=(${res[*]} ${line[$clm]})
done
} <"$file"
printf "%b, " "${res[@]}"\\n\\c
done