使用bash脚本基于数组中的值更新文件列中的值
我有一个包含以下详细信息的文本文件使用bash脚本基于数组中的值更新文件列中的值,bash,shell,file,Bash,Shell,File,我有一个包含以下详细信息的文本文件 #test.txt team_id team_level team_state 23 2 21 4 45 5 我的代码团队中有一个数组statearr=12 34 45。。。我希望能够将数组中的值添加到第三列。数组可以有很多元素,test.txt文件只是我在下面展示的一小部分 文件内容的详细信息: 文本文件只有三个标题。标题由制表符分隔。文件中的行数也与数组中的项目数
#test.txt
team_id team_level team_state
23 2
21 4
45 5
我的代码团队中有一个数组statearr=12 34 45。。。我希望能够将数组中的值添加到第三列。数组可以有很多元素,test.txt文件只是我在下面展示的一小部分
文件内容的详细信息:
文本文件只有三个标题。标题由制表符分隔。文件中的行数也与数组中的项目数相等
因此,我的test.txt如下所示
team_id team_level team_state
23 2 12
21 4 34
45 5 45
(many more rows are present)
到目前为止,我所做的是:我没有看到文件在第三列中有更新值
# Write the issue ids to file
for item in "${teamstatearr[@]}"
do
printf '%s\n' "item id in loop: ${item}"
awk -F, '{$2=($item)}1' OFS='\t', test.txt
done
如果有人能帮我找到最简单有效的方法,我将不胜感激。如果您不介意稍微不同的表格布局,您可以:
teamsstatearr=(12 34 45)
{
# print header
head -n1 test.txt
# combine the remaining lines of test.txt and the array values
paste <(tail -n+2 test.txt) <(printf '%s\n' "${teamsstatearr[@]}")
# use `column -t` to format the output as table
} | column -t
要将输出写入同一文件,可以将输出重定向到新文件,并使用mv覆盖原始文件:
或者使用具有相同输出的awk和column:
teamsstatearr=(12 34 45)
awk -v str="${teamsstatearr[*]}" '
BEGIN{split(str, a)} # split `str` into array `a`
NR==1{print; next} # print header
{print $0, a[++cnt]} # print current line and next array element
' test.txt | column -t
此代码是否将内容写回test.txt文件?你能确认我不明白这一行的目的吗?NR==1{print;next}print头,你从哪里得到cnt的。我看不到它之前在哪里初始化过。我是bash脚本新手,请原谅我问了一些愚蠢的问题。您只需打印代码,但我要求能够将更新列写回test.txt文件。请更新代码更新答案。cnt变量不需要在awk中初始化。如果第一次使用该变量,则默认值为0,因此[++cnt]在第一次调用时从[1]获取值。使用与bash示例中相同的方法。将输出重定向到临时文件,然后覆盖原始文件:awk。。。test.txt |列-t>temp&mv temp test.txt
teamsstatearr=(12 34 45)
{
head -n1 test.txt
paste <(tail -n+2 test.txt) <(printf '%s\n' "${teamsstatearr[@]}")
} | column -t > temp && mv temp test.txt
teamsstatearr=(12 34 45)
{
head -n1 test.txt
paste <(tail -n+2 test.txt) <(printf '%s\n' "${teamsstatearr[@]}")
} | column -t | sponge test.txt
teamsstatearr=(12 34 45)
awk -v str="${teamsstatearr[*]}" '
BEGIN{split(str, a)} # split `str` into array `a`
NR==1{print; next} # print header
{print $0, a[++cnt]} # print current line and next array element
' test.txt | column -t