Run a script over multiple files in unix

2020-06-17 05:11发布

Started to learn some shell scripting. I have a perl script that runs on one file. How would I write a shell script to run the perl script a bunch of times on all files with keyword "filename" in it?

So in English,

for /filename/ in filenames  
    perl myscript.pl completefilename

Thanks.

标签: unix shell
8条回答
何必那么认真
2楼-- · 2020-06-17 05:24

And if you have spaces in your filenames, use the old standby

find . -maxdepth 1 -print0 | xargs -0 perl myscript.pl
查看更多
劳资没心,怎么记你
3楼-- · 2020-06-17 05:27

In bash:

files=`ls -1 *`
for $file in $files;
do
    perl myscript.pl $file;
done
查看更多
Summer. ? 凉城
4楼-- · 2020-06-17 05:30

One liner:

$ for file in filename1 filename2 filename3; do perl myscript $file; done

Instead of the space separated list of filenames you can also use wildcards, for instance:

$ for file in *.txt *.csv; do perl myscript $file; done

查看更多
趁早两清
5楼-- · 2020-06-17 05:30

FILES="keyword"

for f in "$FILES" do perl myscript.pl $f done

From http://www.cyberciti.biz/faq/bash-loop-over-file/

查看更多
虎瘦雄心在
6楼-- · 2020-06-17 05:34

I personally use the zsh shell, which gives you a very nice way to run a command recursively on a set of subdirectories. It also allows you to change the suffix of the file, which is handly when using lame to create MP3 files of .wav files:

for i in **/*.wav; lame $i $i:r.mp3

You can also pipe the output of one command to another, which I something I use frequently when I'm downloading a number of bittorrent files and want to see the percentage that each download has completed:

for i in **/*.txt; grep -H percent $i | tail -1

查看更多
再贱就再见
7楼-- · 2020-06-17 05:36
find . -name "filename*" -exec perl myscript.pl '{}' \; 
查看更多
登录 后发表回答