Shell脚本用于打印特定索引的行值

时间:2016-09-26 18:14:00

标签: linux shell

我有如下输出:

S0     S1     E      O      P     YGC     YGCT    FGC    FGCT     GCT    LGCC                 GCC
31.59   0.00  20.69  44.69  59.67   8296   14.909 129667  621.433  636.342 CMS Final Remark     No GC

现在我需要选择特定的键和值并打印如下:

S0,P,FGCT
31.59,59.67,621.433

如何在每一行中选择特定的索引值? 请建议

4 个答案:

答案 0 :(得分:1)

一种方法可以是

Random rand = new Random(); // use a single Random generator
int max = ...;
for (int numbers = 1; numbers <= 140; numbers++) {      
    uniqueKeys.add(rand.nextInt(max)); // use the same range for all 
                                       // the random generated numbers
}

或者如果在某个变量中

awk '{ print $1 " " $5 " " $9 }' MyFileName

EDIT2: 这也适用(在Linux上测试)

echo $MyContent | awk '{ print $1 " " $5 " " $9 }'

答案 1 :(得分:0)

以下是纯本机shell(bash 4.x或更新版)中的实现步骤:

## Read keys and values each into a separate array
## Note: If input is tab-delimited, have IFS=$'\t' set for these reads
{ read -r -a keys; read -r -a values; }

## Combine those two arrays into a single associative array mapping keys to values
declare -A content=( )
for idx in "${!keys[@]}"; do
  k=${keys[$idx]}
  v=${values[$idx]}
  content[$k]=$v
done

## ...take as input our set of desired keys...
desired_keys=( S0 P FGCH )

## ...and collect the associated values for each
output=( )
for k in "${desired_keys[@]}"; do
  output+=( "${content[$k]}" )
done

## With that done, we can emit our desired output:
IFS=,
printf '%s\n' "${desired_keys[*]}" "${output[*]}"

答案 2 :(得分:0)

awk是你的朋友。

[dev]$ cat myfile.txt 
S0     S1     E      O      P     YGC     YGCT    FGC    FGCT     GCT    LGCC                 GCC
31.59   0.00  20.69  44.69  59.67   8296   14.909 129667  621.433  636.342 CMS Final Remark     No GC


[dev]$ awk -F " " 'NR==0{print;next} {printf "%s %s %s \n",$1,$5,$9}' myfile.txt 
S0 P FGCT 
31.59 59.67 621.433 

按照愿望移动$1,$5,$9。请确保为每个新选择的值添加额外的%s,例如$7 ..

示例:printf "%s %s %s %s \n",$1,$5,$9,$7

您还可以通过执行以下操作将分隔符从空格更改为短划线:

printf "%s-%s-%s \n",$1,$5,$9 

printf "%s,%s,%s \n",$1,$5,$9 

我希望你觉得这很有帮助。

答案 3 :(得分:0)

您可以使用echocut

进行一些小修
data1="S0     S1     E      O      P     YGC     YGCT    FGC    FGCT     GCT    LGCC                 GCC"
data2="31.59   0.00  20.69  44.69  59.67   8296   14.909 129667  621.433  636.342 CMS Final Remark     No GC"

echo $data1 | cut -f 1,5,9 -d " " --output-delimiter=','
echo $data2 | cut -f 1,5,9 -d " " --output-delimiter=','

通过将值存储在中间变量中并使用echo打印它们,您将只在值之间获得单个空格。

这与不带引号的回调基本相同:

echo S0     S1     E      O      P     YGC     YGCT    FGC    FGCT     GCT    LGCC                 GCC | cut -f 1,5,9 -d " " --output-delimiter=','
echo 31.59   0.00  20.69  44.69  59.67   8296   14.909 129667  621.433  636.342 CMS Final Remark     No GC | cut -f 1,5,9 -d " " --output-delimiter=','

只有在您的值中没有空格(显然)时才会有效。