我是Bash脚本新手。我正在努力理解这一特定的代码行。请帮忙。
old_tag = awk -v search="$new_tag" -F" " '$1==search { a[count] = $2; count++; } END { srand();print a[int(rand()*(count-1))+1] }' $tag_dir/$file
[ -z "$new_tag" ] && break
答案 0 :(得分:0)
代码似乎不正确。使用old_tag = awk
,代码会尝试在var old_tag
中输出awk命令的结果。应该在=
周围没有空格的情况下完成var的赋值,并且命令应该包含在$(..)
中。它可能是原始代码中的支持者,这些是折旧的,并且在SO中用于格式化
使用示例输入文件可以更容易地回答您的问题,但尝试解释假设输入行如
apple x1
car a
rotten apple
tree sf
apple x5
car a4
apple x3
我切换了old_tag
和new_tag
,这似乎更有意义。
new_tag=$(awk -v search="$old_tag" -F" " '
$1==search { a[count] = $2; count++; }
END { srand(); print a[int(rand()*(count-1))+1] }
' $tag_dir/$file)
[ -z "$new_tag" ] && break
此鳕鱼会尝试通过搜索$tag_dir/$file
中的旧标记来替换以找到新标记。当标签出现多次时,请随机选择其中一行。
该代码更详细解释:
# assign output to variable new_tag
new_tag=$(..)
# use awk program
awk ..
# Assign the valuo of old_tag to a variable "search" that can be used in awk
-v search="$old_tag"
# Different fields seperated by spaces
-F" "
# The awk programming lines
' .. '
# Check first field of line with the variable search
$1==search { .. }
# When true, store second field of line in array and increment index
a[count] = $2; count++;
# Additional comands after processing everything
END {..}
# Print random index from array
srand(); print a[int(rand()*(count-1))+1]
# Use file as input for awk
$tag_dir/$file
# Stop when no new_tag has been found
[ -z "$new_tag" ] && break
# I would have preferred the syntax
test -z "${new_tag}" && break
使用示例输入和old_tag="apple"
,代码将找到以apple作为第一个单词的行
apple x1
apple x5
apple x3
单词x1 x5 x3
存储在数组a
中,其中一个随机分配给new_tag
。