Bash script for looping through files

时间:2015-05-12 23:09:14

标签: bash

I have several files in a folder, e.g. in \home\ directory. Now I want a bash script which loops through all the files and executes a command for each file (the command uses the file name).

How can I do this?

4 个答案:

答案 0 :(得分:2)

ofs= $('#ball').offset();

if(ofs.left < maxLeft || ofs.left+ballWidth  > maxRight ||
   ofs.top  < maxTop  || ofs.top +ballHeight > maxBottom
  ) {
  $('#ball').css({
    top : '-=' + y,
    left: '-=' + x
  });
}

答案 1 :(得分:1)

Something like this might help you get started:

main()
{
    List<obj> objList = new objList<>;
    doReverse(objList);
}
//By the end of your main GC will collect objList

If there are folders too in that directory then you will need to check for files:

add this line immediately after for file in /home/directory/*; do filename=${file##*/} echo "$filename" ##execute command here with $filename done :

for..do

If you want to ignore symbolic links, then:

[[ ! -f $file ]] && continue

Additional (according to comment):

You can check if a string (mask) is in the file name or not with:

[[ ! -f $file || -L $file ]] && continue

You can modify the filename like this:

if [[ $filename == *mask* ]];then
echo it's there
else
echo It's not there
fi

#assuming you want to add mask before the extension newfilename="${filename%%.*}_mask${filename#*.}" echo "$newfilename" is the part of ${filename%%.*} without extension

$filename is the extension of ${filename#*.}

答案 2 :(得分:0)

There are several ways:

  1. With SELECT id, picture FROM media WHERE userID = $friend->user_id AND relation = 'profile_picture' UNION ALL SELECT -1 id, 'default.png' picture ORDER BY id DESC LIMIT 1

xargs is useful for take a list from xargs and use each of them with a command, example:

stdin
  1. With a ls yourdir/ | xargs yourcmd loop

Loop can be use with a list of words or with a wildcard, example:

for
  1. With for i in *; do yourcmd $i ; done # for i in `ls youdir`; do yourcmd $i ; done # Never do that

find allow to do it in one command, example (from GNU find man):

find

Runs 'file' on every file in or below the current directory. Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is simi- larly protected by the use of a backslash, though ';' could have been used in that case also.

答案 3 :(得分:0)

If you want to iterate only over files, then:

<table>
    <thead>
        <tr>
            <td colspan="2">A</td>
            <td>B</td>
            <td>C</td>
        </tr>
    </thead>
</table>

For example if you wanted to change access rights of only files in a current directory (but leave all the directories untouched):

find <your-dir> -type f | xargs <your-cmd>

The find . -type f | xargs -n 1 chmod u+rw part tells -n 1 to invoke xargs for each directory separately (which is not the most efficient in this case, but you should get the idea).