如何sed
报告文件中大小不为 21 的任何第一条记录?
我不想sed
扫描整个文件并在找到第一个大小不为 21 的记录后立即退出。
答案1
基于此回答你之前的问题
sed -n '/^.\{21\}$/! {p;q;}' file
答案2
使用awk
(这将是最简单的):
awk 'length != 21 { printf("Line of length %d found\n", length); exit }' file
或者,作为 shell 脚本的一部分,
if ! awk 'length != 21 { exit 1 }' file; then
echo 'Line of length != 21 found (or awk failed to execute properly)'
else
echo 'All lines are 21 characters (or the file is empty)'
fi
使用sed
:
sed -nE '/^.{21}$/!{p;q;}' file
有了GNU sed
,你就可以做到
if ! sed -nE '/.{21}$/!q 1' file; then
echo 'Line with != 21 characters found (or sed failed to run properly)'
else
echo 'All lines are 21 characters (or file is empty)'
fi
答案3
使用 GNU grep
:
if line=$(grep -Exnvm1 '.{21}' < file); then
printf >&2 'Found "%s" which is not 21 characters long\n' "$line"
fi
(-n
以上包括行号)