且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

awk的反向线条和文字

更新时间:2023-02-25 22:55:18

千电子伏的解决方案看起来扭转每个字的文本。你比如输出不显示,但他的关键点是使用功能。

Kev's solution looks to reverse the text in each word. You example output doesn't show that, but his key point is to use a function.

您有code你需要,你只需要重新安排它一点。

You have the code you need, you just need to rearrange it a little.

cat file1
aa bb cc
foo do as

cat commandFile

function reverse( line ) {
  n=split(line, tmpLine)
  for (j=n; j>0; j--) {
    printf("%s ",tmpLine[j] )
  }

}
# main loop
{ a[NR]=$0 }

# print reversed array
END{ for(i=NR; i>0; i--) printf( "%s\n",  reverse(a[i]) ) }

运行

 awk -f commandFile file1

输出

as do foo
cc bb aa

有一对夫妇的我做了,用细微的变化 N =分(线,tmpLine)...打印tmpLine [J] ,是分析的常用方法输入的函数中的一行打印出来。我不认为$ 1经销商也有从一个数组(你一个[I]值)传递一个取值范围,所以我改成了split..tmpLine [J]。我还发现,从端部的'我'变量被关在范围中的函数逆转,所以我改变了到J来消除歧义的情况。

There were a couple of minor changes I made, using n=split(line, tmpLine) ... print tmpLine[j], is a common method of parsing a line of input in a function to print it out. I don't think the $1 vars have scope from a value passed in from an array (your a[i] value), so I changed it to split..tmpLine[j]. I also found that the 'i' variable from END section was kept in scope in the function reverse, so I changed that to j to disambiguate the situation.

我必须弄清楚一些事情,所以下面是我使用的调试版本。

I had to figure out a few things, so below is the debug version that I used.

如果你将有机会获得呆子,那么你就应该好好学习如何使用调试器可用。如果你使用的系统上的awk / GAWK / NAWK没有一个调试器,那么这是理解什么是您的code发生的一种方法。如果你重定向你的程序输出到文件或管道,如果你的系统支持的/ dev /标准错误的符号,你可以打印调试行出现,即。

If you're going to have access to gawk, then you'll do well to learn how to use the debugger that is available. If you're using awk/gawk/nawk on systems without a debugger, then this is one method for understanding what is happening in your code. If you're redirecting your programs output to a file or pipe, AND if you system supports "/dev/stderr" notation, you could print the debug lines there, i.e.

 #dbg print "#dbg0:line=" line > "/dev/stderr"

有些系统有其他的符号来访问标准错误,所以如果你会更这样做,这是值得找出哪些是可用的。

Some systems have other notations for accessing stderr, so if you'll be doing this much, it is worthwhile to find out what is available.

cat commandFile.debug
function reverse( line ) {
  n=split(line, tmpLine)
  #dbg print "#dbg0:line=" line
  #dbg print "#dbg1:n=" n "\tj=" j "\ttmpLine[j]=" tmpLine[j]
  for (j=n; j>0; j--) {
    #dbg print "#dbg2:n=" n "\tj=" j "\ttempLine[j]=" tmpLine[j]
    printf("%s ",tmpLine[j] )
  }

}
# main loop
{ a[NR]=$0 }

# print reversed array
#dbg END{ print "AT END";  for(i=NR; i>0; i--) printf( "#dbg4:i=%d\t%s\n%s\n", i, a[i] , reverse(a[i])
 ) }
END{ for(i=NR; i>0; i--) printf( "%s\n",  reverse(a[i]) ) }

我希望这有助于。

I hope this helps.