Skip to content

Commit

Permalink
add new md
Browse files Browse the repository at this point in the history
  • Loading branch information
LYDongD committed Aug 15, 2019
1 parent dbd976b commit 19924b7
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
1 change: 1 addition & 0 deletions SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@
* [快速生成md图片链接](dev-ops/shell/script/pushimage.md)
* [基于地理位置查询脚本](dev-ops/shell/script/geo_search.md)
* [分组统计](dev-ops/shell/script/statistic.md)
* [行转列](dev-ops/shell/script/printCol.md)
* [文本处理](dev-ops/shell/text/README.md)
* [shell](dev-ops/shell/text/shell.md)
* [打印](dev-ops/shell/text/echo.md)
Expand Down
78 changes: 78 additions & 0 deletions dev-ops/shell/script/printCol.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
## 行转列


### 问题

给定一个文件,包含多行数据,每行是由以空格为分隔符的单词组成

要求按列打印(行转列)

例如:

```
name age
alice 21
ryan 30
```

脚本处理好,输出为:

```
name alice ryan
age 21 30
```


### 解法1

使用双层嵌套循环,外层按列遍历,内层按行遍历即可

遍历行时,拼接字符串,遍历完成后打印结果即为当前列结果

```
#!/bin/bash
col=$(head -n1 file.txt | awk '{print NF}')
for((i=1;i<=$col;i++))
do
while read line; do
tmp=$(echo $line | awk '{print $v1}' v1="$i")
str=${str}" $tmp"
done < file.txt
echo $str
str=""
done
```

### 解法2

使用awk逐行处理,用数组保存每列的结果

第一行:初始化数组,每列占位一个元素

其他行: 根据列取出指定元素进行拼接

所有行处理完成后,每个元素都保存一个完整列,最后遍历数组打印即可

```
awk '
{
for (i = 1; i <= NF; i++) {
if(NR == 1) {
s[i] = $i;
} else {
s[i] = s[i] " " $i;
}
}
}
END {
for (i = 1; s[i] != ""; i++) {
print s[i];
}
}' file.txt
```

0 comments on commit 19924b7

Please sign in to comment.