简体   繁体   English

部分文件名作为Shell脚本输入

[英]Partial File Name as Shell Script Input

I am trying to create a shell script that takes a partial file name as its input and then does operations on the files with the matching names. 我正在尝试创建一个将部分文件名作为输入的shell脚本,然后对具有匹配名称的文件进行操作。 For example, I have three files sample1.txt,sample2.txt and sample3.txt and this is my script 例如,我有三个文件sample1.txt,sample2.txt and sample3.txt ,这是我的脚本

#!bin/bash

VALUE=$1
VALUE2=$2
FILE_NAME=$3

echo $FILE_NAME

And I run it with this command 我用这个命令运行它

sh myscript.sh arg1 arg2 sample*

But I get this as the output 但是我得到这个作为输出

sample3.txt (sample2.txt)

But what I want is 但是我想要的是

sample1.txt
sample2.txt
sample3.txt

How could I do this? 我该怎么办?

sample*

get's expanded into (if the files exists, no more files with that name, etc): get扩展为(如果文件存在,则不再具有该名称的文件,等等):

sample1.txt sample2.txt sample3.txt

So when you write: 所以当你写:

sh myscript.sh arg1 arg2 sample*

What you really write, what your script sees is: 您实际编写的脚本看到的是:

sh myscript.sh arg1 arg2 sample1.txt sample2.txt sample3.txt

Your script get's 5 arguments, not 3 您的脚本得到5个参数,而不是3个

Then you can: 那么你也能:

#!bin/bash

VALUE=$1
VALUE2=$2

# shift the arguments to jump over the first two 
shift 2

# print all the rest of arguments
echo "$@"

# ex. read the arguments into an array
FILE_NAME=("$@")
echo "${FILE_NAME[@]}"

Live example at jdoodle . jdoodle的实时示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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