bash 如何在bash脚本中排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14403572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort in bash script?
提问by Christian Dior Howard
Possible Duplicate:
This script wont sort correctly by age
可能重复:
此脚本无法按年龄正确排序
I have absolutaly no idea how to get this script to sort the info in Birthdays.csv by date of birth. I know the sort -n command, however i wish to sort the file birthdays.csv by DOB. How would i go about doing this?
我完全不知道如何让这个脚本按出生日期对 Birthdays.csv 中的信息进行排序。我知道 sort -n 命令,但是我希望按 DOB 对文件birthdays.csv 进行排序。我该怎么做呢?
The below script gets user info and date of birth and then puts these info a file called “birthday.csv”.
下面的脚本获取用户信息和出生日期,然后将这些信息放在一个名为“birthday.csv”的文件中。
I then need to Sort “birthdays.csv” by date of birth and then display this newly sorted information. I also calculate how old each person is by today's date. The problem i have is sorting the info in birthdays.csv by date of birth. Can someone let me know how i would do this sort?
然后我需要按出生日期对“birthdays.csv”进行排序,然后显示这个新排序的信息。我还计算每个人到今天的年龄。我遇到的问题是按出生日期对birthdays.csv 中的信息进行排序。有人可以让我知道我会怎么做吗?
The script is below:
脚本如下:
a=0
while [ $a -lt 2 ];
do
echo Please enter a first name
read firstName
echo Please enter last name
read lastName
echo Please enter phone number
read phoneNumber
echo Please enter date of birth - format dd/mm/yyyy
read dob
echo "$firstName,$lastName,$phoneNumber,$dob" >> Birthdays.csv
echo If you would like to add another person press 1 or enter 2 to proceed
read a
done
INPUT=./Birthdays.csv
OLDIFS=$IFS
IFS=","
[ -f ${INPUT} ] && while read Name Surname Telephone DOB
do
birthMonth=${DOB:0:2}
birthDay=${DOB:3:2}
birthYear=${DOB:6:4}
currentDate=`date +%d/%m/%Y`
currentMonth=${currentDate:0:2}
currentDay=${currentDate:3:2}
currentYear=${currentDate:6:4}
if [[ "$currentMonth" -lt "$birthMonth" ]] || [[ "$currentMonth" -eq "$birthMonth" && "$currentDay" -lt "$$birthDay" ]]
then
let Age=currentYear-birthYear-1
else
let Age=currentYear-birthYear
fi
echo "Name : $Name"
echo "Surname : $Surname"
echo "Telephone : $Telephone"
echo "DOB : $DOB"
echo "Age : $Age"
echo "##########################################"
done < $INPUT
IFS=$OLDIFS
echo $DATE
exit 0;
回答by J Homard
add this line
添加这一行
sort -o $INPUT -n -t , -k4.7,4 -k4.4,4.5 -k4.1,4.2 $INPUT
After
后
INPUT=./Birthdays.csv
回答by just_in
Try -- ### cat Birthdays.csv | sort --field-separator='/' --key=3,5
试试 -- ### cat Birthdays.csv | sort --field-separator='/' --key=3,5

