I'm trying to set the value of a variable to one line of a file, over and over.
for i in {1..5}
do
THIS = "grep -m $i'[a-z]' newdict2" | tail -1
echo $THIS
done
What's the trick to this black magic?
I'm trying to set the value of a variable to one line of a file, over and over.
for i in {1..5}
do
THIS = "grep -m $i'[a-z]' newdict2" | tail -1
echo $THIS
done
What's the trick to this black magic?
使用 sed 运行它实际上比使用 tail 和 grep 的 -m 选项更容易:
for i in {1..5}
do
THIS=$(grep -e '[a-z]' newdict2 | sed -ne "${i}p")
echo "$THIS"
done
如果从 1 到 x 开始,其他解决方法是通过循环读行:
while IFS= read -r THIS; do
echo "$THIS"
done < <(grep -e '[a-z]' newdict2)
并通过 awk:
while IFS= read -r THIS; do
echo "$THIS"
done < (awk '/[a-z]/ && ++i <= 5' newdict2)
另一个初始值不同的 awk 版本:
while IFS= read -r THIS; do
echo "$THIS"
done < (awk 'BEGIN { i = 2 } /[a-z]/ && i++ <= 5' newdict2)
最好找到一次,然后循环遍历它们。
grep -m "$i" '[a-z]' newdict |
nl |
while read i THIS; do
echo "$THIS"
done
如果您不需要$i
循环内的任何内容,请删除nl
并仅read THIS
.
还要注意在变量插值周围使用双引号。