Transpose File
来源:互联网 发布:阶层的算法c语言 编辑:程序博客网 时间:2024/04/26 14:01
Transpose File
Total Accepted: 3876Total Submissions: 18849Difficulty: MediumContributors: Admin
Given a text file file.txt, transpose its content.
You may assume that each row has the same number of columns and each field is separated by the ’ ’ character.
For example, if file.txt has the following content:
name age
alice 21
ryan 30
Output the following:
name alice ryan
age 21 30
解法一:
利用NF个数组进行存储,就是每次遍历一个记录的时候,把第一列放到数组line[1]中,第二列放到数组lien[2]中.....
接下来遍历的时候,然后继续向line[1],line[2]....的后面接数据
代码:
#!/bin/kshtypeset numbergawk '{ for( i=1;i<=NF;i++) { if (str[i] == "") { str[i]=$i } else { str[i]=str[i]" "$i } } } END{ for(i=1;i<=NF;i++) { print str[i] } number=NF } ' t12-file.txt# out of the awk,the value of the number is null, not the value of NFprint "The number is $number"
解法二:
利用cut直接打印出第一列,第二列.....
在cut外定义的变量,可以传进到cut中,既可以在cut中使用cut外面定义和赋值的变量;
同是在cut中对变量的新赋值,也能在cut外面反映出来。
代码:
#! /bin/kshtypeset numbernumber=$(awk '{num=NF} END{print num}' t12-file.txt)for ((i=1;i<=$number;i++ )); do print "This is the \$i: $i" cut -d " " -f $i t12-file.txt |xargs num="hello world"done# the value of num is "hello world"print "The num is $num"
解法三:
利用估计列数的办法,不好的办法。
awk外面定义的变量不能在awk中使用,除非把值传进awk中,否则,在外面定义的变量,在awk中使用是空的。
同理,在awk中改变变量的值,在awk外面也不能反映出来。
代码:
#!/bin/kshawk -F" " 'BEGIN{i=1}{print $i}' t12-file.txt |xargsawk -F" " 'BEGIN{i=2} {print $i}' t12-file.txt |xargsprint "################################"i=1awk -F" " '{print $field}' field=$i t12-file.txt |xargs((i++))awk -F" " '{print $field}' field=$i t12-file.txt |xargs
0 0
- Transpose File
- Transpose File
- Transpose File
- [Leetcode Shell] Transpose File
- leetcode-194 Transpose File
- 【Leetcode Shell】Transpose File
- Leetcode: Transpose File
- [leetcode] Transpose File
- 194. Transpose File
- leetcode 194. Transpose File
- 194. Transpose File
- leetcode194. Transpose File
- 194. Transpose File
- 194. Transpose File
- 194. Transpose File。
- [Leetcode] 194. Transpose File
- Leetcode: Transpose File (shell, awk)
- 194. Transpose File leetcode Bash
- 魔波广告恶意病毒简析
- android 事件分发机制
- 敏捷开发原则
- js中通过split函数分割字符串成数组小例子
- 使用jsp的Form标签填写表单(自动返回提交值)
- Transpose File
- radio、checkbox样式修改
- RecycleView拖拽排序+侧滑删除+侧滑菜单
- 深入理解乐观锁与悲观锁
- API 23 widget.LinearLayout——属性分析
- linux挂载cdrom,并添加本地yum源和局域网yum源
- java程序员需要看的一些书~java程序猿进阶书籍~
- 社交聊天工具哪个比较好?
- 数据挖掘中最容易犯的十大错误