操纵用户输入

时间:2011-01-17 16:01:48

标签: linux bash

我是bash的新手。我试图以下列形式从用户那里获得2个输入:DD / MM / YYYY DD / MM / YYYY(日,月,年一行)。以下是我为dd尝试的内容(我还需要从两个输入中获取MM和YYYY):

dd1=read | cut -d'/' -f1 (I tried this with backquotes and it didn't work)

[用dd1做点什么......]

echo $dd1

$ dd1一直空着。我可以使用一些指针(不是具体的答案)来完成我的作业问题。感谢。

3 个答案:

答案 0 :(得分:2)

你倒退了,试试这个;

read dd1 && echo $dd1|cut -d'/' -f1 

答案 1 :(得分:0)

试一试。它将允许用户输入日期,并将在斜杠上为您分割。

IFS=/ read -r -p "Enter a date in the form DD/MM/YYYY: " dd mm yy

答案 2 :(得分:0)

您是否需要在一行上执行此操作,或者您是否希望用户在一行上输入两个日期?

如果您只需要用户在命令行上输入两个日期,则可以执行以下操作:

read -p "Enter two dates in YY/MM/DD format: " date1 date2

然后,在用户输入两个日期后,您可以解析它们以验证它们的格式是否正确。您可以继续循环,直到日期正确为止:

while 1
do
    read -p "Enter two dates in 'DD/MM/YYY' format: date1 date2
    if [ ! date1 ] -o [ ! date2 ]
    then
       echo "You need to enter two dates."
       sleep 2
       continue
    if
    [other tests to verify date formats...]
    break    # Passed all the tests
done

如果您可以一次输入一个日期,则可以操纵IFS变量以使用斜杠而不是空格作为分隔符。

OLDIFS="$IFS"   #Save the original
IFS="/"
read -p "Enter your date in MM/DD/YYYY format: " month day year
IFS="$OLDIFS"   #Restore the value of IFS

这可以放在while循环中,就像上面的示例一样,您可以验证输入的日期是否正确。

实际上,你可以这样做:

OLDIFS="$IFS"   #Save the original
IFS="/ "   #Note space before quotation mark!
read -p "Enter two dates in MM/DD/YYYY format: " month1 day1 year1 month2 day2 year2
IFS="$OLDIFS"   #Restore the value of IFS
echo "Month #1 = $month1  Day #1 = $day1  Year #1 = $year1"
echo "Month #2 = $month1  Day #2 = $day2  Year #2 = $year2"

并在同一命令行中获取两个日期。

相关问题