我是新手……我需要一个脚本,它接收一个目录作为参数并打印 15 到 50 行之间的文件的名称,但我不知道如何使用-sentence 中的wc输出if:
#!/bin/bash
for f in `ls`; do
echo "File -> $f"
cat $f | wc -l
done
Run Code Online (Sandbox Code Playgroud)
我如何接收参数?以及如何将wc输出分配给变量?
参数可以作为$1、$2等接收,也可以作为$*所有参数接收。
还有阵列$@,其通常被用作"$@"作为一个更好的版本的$*。另一种可能的用法是${@:3}“所有参数以 3rd 开头”。
要获取命令的输出,请使用$( ... )或其旧形式` ... `。通常建议始终使用,$()因为它可以嵌套,例如blah=$(cat /blah/$(blah)/blah).
#!/usr/bin/env bash
for dir in "$@"; do
for file in "$dir"/*; do
lines=$(wc -l < "$file")
if (( lines >= 15 && lines <= 50 )); then
echo "File -> $file ($lines lines)"
fi
# another possible syntax:
# if [ "$lines" -ge 15 ] && [ "$lines" -le 50 ]
# or:
# if [[ "$lines" -ge 15 && "$lines" -le 50 ]]
done
done
Run Code Online (Sandbox Code Playgroud)
有用的资源:
| 归档时间: |
|
| 查看次数: |
742 次 |
| 最近记录: |