为什么这段代码不起作用?

为什么这段代码不起作用?

我正在尝试获取这样的输出;

$ sh mod-date-pattern.sh sun
The file sun1.txt was modified on 2007-10-01 at 01:26.
The file sun2.txt was modified on 2007-10-01 at 19:10.
The file morning-sun.txt was modified on 2007-10-01 at 02:53.
The file evening-sun.txt was modified on 2007-10-01 at 02:55.

我的代码是;

Namefile=$1
ExDatefile=$(ls -l $Namefile*)
IFS=' ' array_Datefile=($Exdatefile)
for n in 5 14 22 30 
do 
m=$(($n +1))
o=$(($m +1))
p=$(($n -3))
Mounth=${array_Datefile[$n]}
Day=${array_Datefile[$m]}
Time=${array_Datefile[$o]}
Name=${array_Datefile[$p]}
echo "The file $Name was modified on $Mounth $Day $Time"
done

顺便一提$ExDatefile 的输出是 ;

-rwxr-xr-x@ 1 onurcanbektas staff 2026 May 29 2008 hw1_evening_sun.txt
-rwxr-xr-x@ 1 onurcanbektas staff 2687 May 29 2008 hw1_morning_sun.txt
-rwxr-xr-x@ 1 onurcanbektas staff 243128 May 29 2008 hw1_out_si_wire.txt
-rw-r--r-- 1 onurcanbektas staff 282 Jun 2 10:28 hw1_script.sh
-rw-r--r-- 1 onurcanbektas staff 68 Jun 2 11:49 hw1_script2.sh
-rwxr-xr-x@ 1 onurcanbektas staff 577 May 29 2008 hw1_sun1.txt
-rwxr-xr-x@ 1 onurcanbektas staff 6074 May 29 2008 hw1_sun2.txt

输出是;

$ sh hw1_script2.sh hw1
The file  was modified on   
The file  was modified on   
The file  was modified on   
The file  was modified on   

那么,有什么问题吗?

注:我不确定所提供的信息是否足以回答此问题。如果是的话,请通知我。

Bash 3.2 OS X El Capitan

编辑:

当我直接调用 $array_Datefile[$n] 时,输出是;

[5] [6] [7] [8]
[14] [15] [16] [17]
[22] [23] [24] [25]
[30] [31] [32] [33]

为什么会这样?解析有问题吗?

答案1

好吧,如果你真的想解析ls -l输出,你可以尝试这个:

Namefile=$1
while read perms blocks user group size month day yearortime filename ;do
    echo "The file $filename was modified on $month $day $yearortime"
  done < <(ls -l $Namefile*)

...但如果for $Namefile* ..你最好:

Namefile=$1
for file in $Namefile*;do
    unixtime=$(stat -c %Y "$file")
    printf "The file %s was modified on %(%b %d %Y, %T)T\n" "$file" $unixtime
  done

答案2

这并不完整,但 $(ls -l xxx) 生成一行,而不是每个文件一行。这会扰乱你的解析。

因此,循环遍历 $Namefile*,一次处理一个文件。

答案3

你的索引错了:

for ((m = 5; m < ${#array_Datefile[@]}; m += 9))
do
    d=$((m + 1))
    t=$((m + 2))
    f=$((m + 3))
    Month=${array_Datefile[m]}
    Day=${array_Datefile[d]}
    Time=${array_Datefile[t]}
    Name=${array_Datefile[f]}
    echo "The file $Name was modified on $Month $Day $Time"
done

答案4

我已经解决了;

Namefile=$1
i=-1
for n in $Namefile*
do
ExDatefile=$(ls -l $Namefile* | head $i | tail -1 )
i=$(($i -1))
IFS=' ' array_Datefile=($ExDatefile)
echo "The file ${array_Datefile[8]} was modified ${array_Datefile[5]} ${array_D$
unset ExDatefile
done

输出是;

The file hw1_evening_sun.txt was modified May 29 2008
The file hw1_morning_sun.txt was modified May 29 2008
The file hw1_out_si_wire.txt was modified May 29 2008
The file hw1_script.sh was modified Jun 2 15:20
The file hw1_script2.sh was modified Jun 2 15:16
The file hw1_sun1.txt was modified May 29 2008
The file hw1_sun2.txt was modified May 29 2008

相关内容