假设我读了以下信息,这些信息存储在三个不同的文本文件中(可以更多)
档案1
1 2 rt 45
2 3 er 44
文件2
rf r 4 5
3 er 4 t
er t yu 4
档案3
er tyu 3er 3r
der 4r 5e
edr rty tyu 4r
edr 5t yt5 45
当我读到这些信息时,我希望它将这两个文件中的信息打印成单独的数组,因为现在它们会在同一时间打印出来
现在我有这个脚本同时打印出所有信息
{
TESTd[NR-1] = $2; g++
}
END {
for (i = 0 ; i <= g-1; i ++ ) {
print " [\"" TESTd[i] "\"]"
}
print " _____"
}
但有没有办法读取多个文件并为每个文本文件执行此操作? 喜欢而不是在做 awk -f test.awk 1.txt 2.txt 3.txt
时获得此输出 ["2"]
["3"]
["r"]
["er"]
["t"]
["tyu"]
["4r"]
["rty"]
["5t"]
_____
我得到了这个输出
["2"]
["3"]
_____
["r"]
["er"]
["t"]
_____
["tyu"]
["4r"]
["rty"]
["5t"]
_____
此时读取每个文件最好不是一个选项,因为我将有30个文本文件。
EDIT_ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ 的__ _ __ _ __ _ __ _ __ _ __
如果可能的话,我想在awk中这样做,因为我会做这样的事情
{
PRINTONCE[NR-1] = $2; g++
PRINTONEATTIME[NR-1] = $3
}
END {
#Do this for all arguments once
for (i = 0 ; i <= g-1; i ++ ) {
print " [\"" PRINTONCE[i] "\"] \n"
}
print " _____"
#Do this for loop for every .txt file that is read in as an argument
#for(j=0;j<args.length;j++){
for (i = 0 ; i <= g-1; i ++ ) {
print " [\"" PRINTONEATTIME[i] "\"] \n"
}
print " _____"
}
答案 0 :(得分:1)
根据我的理解,你有一个awk脚本可以工作,你想在许多文件上运行awk脚本,并希望他们的输出之间有一个新行(或 _ ),所以你可以区分哪个输出来自哪个文件。
试试这个bash脚本: -
dir=~/*.txt #all txt files in ~(home) directory
for f in $dir
do
echo "File is $f"
awk 'BEGIN{print "Hello"}' $f #your awk code will take $f file as input.
echo "------------------"; echo;
done
此外,如果您不想对所有文件执行此操作,则可以将for循环写为for f in 1.txt 2.txt 3.txt
。
答案 1 :(得分:0)
如果您不想直接在awk中执行此操作。您可以在bash或zsh中调用它,例如:
for fic in test*.txt; awk -f test.awk $fic
答案 2 :(得分:0)
直接在awk中执行它非常简单:
# define a function to print out the array
function dump(array, n) {
for (i = 0 ; i <= n-1; i ++ ) {
print " [\"" array[i] "\"]"
}
print " _____"
}
# dump and reset when starting a new file
FNR==1 && NR!=1 {
dump(TESTd, g)
delete TESTd
g = 0
}
# add data to the array
{
TESTd[FNR-1] = $2; g++
}
# dump at the end
END {
dump(TESTd, g)
}
N.B。使用delete TESTd
是一个非标准的gawk功能,但问题被标记为gawk所以我认为可以使用它。
或者,您可以使用ARGIND
,ARGV
,ARGC
或FILENAME
中的一个或多个来区分不同的文件。
或者按照https://stackoverflow.com/a/10691259/981959的建议,使用gawk 4,您可以在原始版本中使用ENDFILE
组而不是END
:
{
TESTd[FNR-1] = $2; g++
}
ENDFILE {
for (i = 0 ; i <= g-1; i ++ ) {
print " [\"" TESTd[i] "\"]"
}
print " _____"
delete TESTd
g = 0
}
答案 3 :(得分:-1)
编写bash shell脚本或基本shell脚本。尝试将下面的内容放入test.sh.然后调用/ bin / sh test.sh或/ bin / bash test.sh,查看哪个将起作用
for f in *.txt
do
echo "File is $f"
awk -F '\t' 'blah blah' $f >> output.txt
done
或编写一个bash shell脚本来调用你的awk脚本
for f in *.txt
do
echo "File is $f"
/bin/sh yourscript.sh
done