简体   繁体   中英

bash loop file echo to each file in the directory

I searched a while and tried it by myself but unable to get this sorted so far. My folder looks below, 4 files

1.txt, 2.txt, 3.txt, 4.txt, 5.txt, 6.txt

I want to print file modified time and echo the time stamp in it

#!/bin/bash
thedate= `ls | xargs stat -s | grep -o "st_mtime=[0-9]*" | sed "s/st_mtime=//g"`   #get file modified time
files= $(ls | grep -Ev '(5.txt|6.txt)$') #exclud 5 and 6 text file

for i in $thedate; do
    echo $i >>  $files  
done 

I want to insert each timestamp to each file. but having "ambiguous redirect" error. am I doing it incorrectly? Thanks

In this case, files is a "list" of files, so you probably want to add another loop to handle them one by one.

Your description is slightly confusing but, if your intent is to append the last modification date of each file to that file, you can do something like:

for fspec in [1-4].txt ; do
    stat -c %y ${fspec} >>${fspec}
done

Note I've used stat -c %y to get the modification time such as 2017-02-09 12:21:22.848349503 +0800 - I'm not sure what variant of stat you're using but mine doesn't have a -s option. You can still use your option, you just have to ensure it's done on each file in turn, probably something like (in the for loop above):

stat -s ${fspec} | grep -o "st_mtime=[0-9]*" | sed "s/st_mtime=//g" >>${fspec}

You can not redirect the output to several files as in > $files .

To process several files you need something like:

#!/bin/bash

for f in ./[0-4].txt ; do
    # get file modified time (in seconds)
    thedate="$(stat --printf='%Y\n' "$f")"   
    echo "$thedate" >> "$f"  
done 

If you want a human readable time format change %Y by %y :

thedate="$(stat --printf='%y\n' "$f")"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM