如何編寫一個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