简体   繁体   English

bash反复打印一行中的第一到第n列

[英]bash print first to nth column in a line iteratively

I am trying to get the column names of a file and print them iteratively. 我正在尝试获取文件的列名并迭代地打印它们。 I guess the problem is with the print $i but I don't know how to correct it. 我猜问题出在print $i但我不知道如何纠正它。 The code I tried is: 我试过的代码是:

#! /bin/bash
for i in {2..5}
do
  set snp = head -n 1 smaller.txt | awk '{print $i}'
  echo $snp
done

Example input file: 输入文件示例:

ID Name Age Sex State Ext
1  A    12   M    UT  811
2  B    12   F    UT  818

Desired output: 所需的输出:

Name 
Age
Sex 
State
Ext

But the output I get is blank screen. 但是我得到的输出是黑屏。

You'd better just read the first line of your file and store the result as an array: 您最好只read文件的第一行并将结果存储为数组:

read -a header < smaller.txt

and then printf the relevant fields: 然后printf相关字段:

printf "%s\n" "${header[@]:1}"

Moreover, this uses only, and involves no unnecessary loops. 而且,这仅使用 ,并且不涉及不必要的循环。

Edit. 编辑。 To also answer your comment, you'll be able to loop through the header fields thus: 为了也回答您的评论,您将能够遍历标题字段,从而:

read -a header < smaller.txt
for snp in "${header[@]:1}"; do
    echo "$snp"
done

Edit 2. Your original method had many many mistakes. 编辑2。您的原始方法有很多错误。 Here's a corrected version of it (although what I wrote before is a much preferable way of solving your problem): 这是它的更正版本(尽管我之前写的是解决问题的更可取的方法):

for i in {2..5}; do
    snp=$(head -n 1 smaller.txt | awk "{print \$$i}")
    echo "$snp"
done
  • set probably doesn't do what you think it does. set可能无法执行您认为的操作。
  • Because of the single quotes in awk '{print $i}' , the $i never gets expanded by . 由于awk '{print $i}'中的单引号导致$i永远不会被扩展。
  • This algorithm is not good since you're calling head and awk 4 times, whereas you don't need a single external process. 该算法不好,因为您要调用headawk 4次,而您不需要单个外部进程。

Hope this helps! 希望这可以帮助!

您可以使用awk本身进行打印:

awk 'NR==1{for (i=2; i<=5; i++) print $i}' smaller.txt

The main problem with your code is that your assignment syntax is wrong. 代码的主要问题是分配语法错误。 Change this: 更改此:

set snp = head -n 1 smaller.txt | awk '{print $i}'

to this: 对此:

snp=$(head -n 1 smaller.txt | awk '{print $i}')

That is: 那是:

  • Do not use set . 不要使用set set is for setting shell options, numbered parameters, and so on, not for assigning arbitrary variables. set用于设置外壳程序选项,编号参数等,而不用于分配任意变量。
  • Remove the spaces around = . 删除=周围的空格。
  • To run a command and capture its output as a string, use $(...) (or `...` , but $(...) is less error-prone). 要运行命令并将其输出捕获为字符串,请使用$(...) (或`...` ,但是$(...)不太容易出错)。

That said, I agree with gniourf_gniourf's approach. 也就是说,我同意gniourf_gniourf的方法。

Here's another alternative; 这是另一种选择。 not necessarily better or worse than any of the others: 不一定比其他任何一个更好或更糟:

for n in $(head smaller.txt)
do
  echo ${n}
done

somthin like somthin喜欢

  for x1 in $(head -n1 smaller.txt );do 
      echo $x1
  done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM