处理多个文件名的 Unix 脚本

发布于 2024-09-27 06:11:03 字数 305 浏览 0 评论 0原文

我正在编写一个脚本,用于对文件中的文本进行折叠、排序和计数。我需要设计该程序,以便如果在命令行上给出多个文件名,它会一个接一个地单独处理每个文件名。我想我可以写一个循环,但我对这些还不太了解,所以如果可能的话想尝试其他选择。是否可以添加其他选项,以便可以在命令行中输入多个文件名?

如果测试 $# -lt 1 然后 echo "用法: $0 输入至少一个 DNA 文件名" 出口 菲 如果测试-r $* 然后 折叠 -w3 $* |排序| uniq-c|排序-k1,1nr -k2 否则
echo“用法:$*必须可读” 出口 菲尼娜

I'm writing a script that will fold, sort and count text in a file. I need to design the program so that, if it is given multiple filenames on the command line, it processes each one separately, one after the other. I think I could write a loop but I don't know that much about those yet so if possible would like to try other options. Are there other options that I can add to this so more than one file name can be entered in the command line?

if test $# -lt 1
then
echo "usage: $0 Enter at least one DNA filename"
exit
fi
if test -r $*
then
fold -w3 $* | sort | uniq -c | sort -k1,1nr -k2
else
echo "usage: $* must be readable"
exit
fi

Nena

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

司马昭之心 2024-10-04 06:11:03

for 循环在这里是合适的。以下形式用于迭代位置参数:

for f; do
   # do work here using "$f" as the current argument
done

这相当于更详细的版本:

for f in "$@"; do
   # do work here using "$f" as the current argument
done

for loop will be appropriate here. The following form is used to iterate over positional arguments:

for f; do
   # do work here using "$f" as the current argument
done

This is equivalent to a more verbose version:

for f in "$@"; do
   # do work here using "$f" as the current argument
done
娇妻 2024-10-04 06:11:03

您可以使用 while 循环和 shift 来逐一迭代命令行参数,如下所示:

if test $# -lt 1  # insufficient arguments.
then
  echo "usage: $0 Enter at least one DNA filename"
  exit
fi

# loop through the argument on by one.
# till their number($#) becomes 0.
while test $# -gt 0  
do    
if test -r "$1"  # use $1..$* represent all arguments.
then
  fold -w3 "$1" | sort | uniq -c | sort -k1,1nr -k2
else
  echo "usage: $1 must be readable"
  exit
fi

# shift so that 2nd argument now comes in $1.
shift

done

You can use a while loop and shift to iterate through the command line arguments one by one as:

if test $# -lt 1  # insufficient arguments.
then
  echo "usage: $0 Enter at least one DNA filename"
  exit
fi

# loop through the argument on by one.
# till their number($#) becomes 0.
while test $# -gt 0  
do    
if test -r "$1"  # use $1..$* represent all arguments.
then
  fold -w3 "$1" | sort | uniq -c | sort -k1,1nr -k2
else
  echo "usage: $1 must be readable"
  exit
fi

# shift so that 2nd argument now comes in $1.
shift

done
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文