如何在bash中使用if语句计数字符?



在bash中使用if语句,我想计算1000字节文件的字符数。如果文件大于1000字节,那么我希望它回显"跳过文件名">

#!/bin/bash
FILES=$(/usr/bin/ls $@)
echo $FILES $@
for f in $FILES
do
echo "Processing $f file..."    
if [ $FILES | wc -c) -gt 1000 ]
then
echo "Skipping $"
elif [ $FILES | wc -c) -eq 1000 ]
then
# count number of characters and output that for file $f
wc -c $f
fi
done

我就是这么做的吗?

cat "$f"读取文件,用wc -c计算字节数,然后用... -gt 1000测试结果是否大于1000。

...
if [ $(cat "$f" | wc -c) -gt 1000 ]; then
...
else
...
fi
...

类似这样,不使用ls

#!/usr/bin/env bash
shopt -s nullglob ##: Just in case there are no files.
files=(*)
for f in "${files[@]}"; do
printf 'Processing %s file...n' "$f"
byte_count=$(wc -c < "$f")
if (( byte_count > 1000 )); then
printf 'Skipping %sn' "$f"
elif (( byte_count == 1000 )); then
printf '%d: %sn' "$byte_count" "$f"
fi
done

  • 它需要更多的错误检查,如如果没有文件或如果正在处理的文件不是文本文件等。

  • 参见如何检查目录是否为空?我如何检查任何*。MPG文件,或者数一下有多少?


使用您的"$@"逻辑从您的帖子。考虑到@kvantour在评论中提到的内容

#!/usr/bin/env bash
files=("$@")
for f in "${files[@]}"; do
[[ -e $f ]] || {
printf '%s no such file or directory skipping...n' "$f"
continue
}
[[ -d $f ]] && {
printf '%s is a directory skipping...n' "$f"
continue
}
printf 'Processing %s file...n' "$f"
byte_count=$(wc -c < "$f")
if ((  byte_count > 1000 )); then
printf '%s has more than 1000 bytes.n' "$f"
elif (( byte_count == 1000 )); then
printf '%s has %d bytes.n' "$f" "$byte_count"
else
printf '%s has less than 1000 bytes.n' "$f"
fi
done

第二个脚本可以使用文件作为绝对路径或相对路径的参数运行。假设脚本的名称为myscript

./myscript file1 file2 file2

./mscrypt *.mp4 *.mp3 *.txt *.csv

或者只是一个普通的glob

./myscript *

带绝对路径

./myscript /path/to/file

./myscript /path/to/*.mp3

或者只是一个普通的glob

./myscript /path/to/*

文件类型的测试可以改进。参见help testfile命令。比如:

file --mime-type -b file.txt

如果您的file命令支持

最新更新