该系列是基于牛客Shell题库,针对具体题目进行查漏补缺,学习相应的命令。
刷题链接:牛客题霸-Shell篇。
该系列文章都放到专栏下,专栏链接为:《专栏:Linux》。欢迎关注专栏~
本文知识预告:
rs
命令,这个命令不常用,了解即可;xargs
命令转置的功能,以及方法四中添加数字用以排序的技巧。总的来说,这道题仍然是awk
命令的扩展。写一个bash脚本来转置文本文件nowcoder.txt中的文件内容。文件中每行列数相同,并且每个字段由空格分隔。假设 nowcoder.txt 内容如下:
job salary
c++ 13
java 14
php 12
你的脚本应当输出(以词频升序排列):
job c++ java php
rs
:reshape a data array
rs
读取标准输入,将每行解释为数组中一行空白的分隔条目,根据选项转换数组,并将其写入标准输出。无参数时,它将流输入转换为便于终端查看的列格式,即如果长度(以字节为单位!).
-c[x] |
Input columns are delimited by the single character x. A missing x is taken to be ‘^I’. |
---|---|
-T |
Print the pure transpose of the input, ignoring any rows or cols specification. |
-z |
Shrink column widths to fit the largest entries appearing in them. |
具体细节,可以输入以下命令查看:
man rs
a=$(cat nowcoder.txt | awk '{print $1}')
b=$(cat nowcoder.txt | awk '{print $2}')
echo $a
echo $b
awk
+xargs
转置cNum=$(awk '{print NF}' nowcoder.txt | uniq)
for i in $(seq 1 $cNum); do
cat nowcoder.txt | awk -v var=$i '{print $var}' | xargs
done
拆分步骤:
lucky@DESKTOP-VQ8KID4:~$ awk '{print NF}' nowcoder.txt | uniq
2
xargs
命令输出,就可达到了转置的目的lucky@DESKTOP-VQ8KID4:~$ cat nowcoder.txt | awk -v var=1 '{print $var}' | xargs
job c++ java php
lucky@DESKTOP-VQ8KID4:~$ cat nowcoder.txt | awk -v var=2 '{print $var}' | xargs
salary 13 14 12
cNum=$(awk '{print NF}' nowcoder.txt | uniq)
for i in $(seq 1 $cNum); do
cat nowcoder.txt | awk -v var=$i '{print $var}' | xargs
done
awk
命令搭配for
循环lucky@DESKTOP-VQ8KID4:~$ awk '{for(i=1;i<=NF;i++) a[i]=a[i]$i" "}END{for(x in a) print a[x]}' nowcoder.txt
job c++ java php
salary 13 14 12
awk
添加数字,排序,直接转置lucky@DESKTOP-VQ8KID4:~$ awk '$1="1."NR","$1,$2="2."NR","$2' nowcoder.txt | tr " " "\n" | sort -n | awk -F "," '{print $2}' | tr "\n" " " | awk -F" " '$5="\n"$5'
job c++ java php
salary 13 14 12
拆分步骤:
lucky@DESKTOP-VQ8KID4:~$ awk '$1="1."NR","$1,$2="2."NR","$2' nowcoder.txt
1.1,job 2.1,salary
1.2,c++ 2.2,13
1.3,java 2.3,14
1.4,php 2.4,12
lucky@DESKTOP-VQ8KID4:~$ awk '$1="1."NR","$1,$2="2."NR","$2' nowcoder.txt | tr " " "\n"
1.1,job
2.1,salary
1.2,c++
2.2,13
1.3,java
2.3,14
1.4,php
2.4,12
lucky@DESKTOP-VQ8KID4:~$ awk '$1="1."NR","$1,$2="2."NR","$2' nowcoder.txt | tr " " "\n" | sort -n
1.1,job
1.2,c++
1.3,java
1.4,php
2.1,salary
2.2,13
2.3,14
2.4,12
,
分隔出两列,提取出第二列lucky@DESKTOP-VQ8KID4:~$ awk '$1="1."NR","$1,$2="2."NR","$2' nowcoder.txt | tr " " "\n" | sort -n | awk -F "," '{print $2}'
job
c++
java
php
salary
13
14
12
lucky@DESKTOP-VQ8KID4:~$ awk '$1="1."NR","$1,$2="2."NR","$2' nowcoder.txt | tr " " "\n" | sort -n | awk -F "," '{print $2}' | tr "\n" " "
job c++ java php salary 13 14 12
lucky@DESKTOP-VQ8KID4:~$ awk '$1="1."NR","$1,$2="2."NR","$2' nowcoder.txt | tr " " "\n" | sort -n | awk -F "," '{print $2}' | tr "\n" " " | awk -F" " '$5="\n"$5'
job c++ java php
salary 13 14 12
rs
(拓展方法)这个命令牛客没有哈,自己知道就行。
lucky@DESKTOP-VQ8KID4:~$ rs -Tzc' ' < nowcoder.txt
job c++ java php
salary 13 14 12