逐行读取shell bash中的字符串变量并获取每行的数字

时间:2014-06-15 18:47:50

标签: bash shell

我想做标题所说的。另外,希望跳过第一行。我有这个代码

#!/bin/bash

output="This\nis 3\na 7\n2 string"
if echo "$output" | grep -q "no"; then   #Just looking for substring "no"
    echo "No running jobs were found";
else
   #read < $output                     #Skip first line
   while read line                   #read the output line by line
   do
      jobID = grep -o '[0-9]*' line     #Take the number (JobID) of each line
      echo $jobID                   #Use the ID to stop the job
   done <<< "$output"
fi

但是没有wotk。有任何想法吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

我修改了输入字符串,名为&#34;输出&#34;通过在第一个字段(行)中添加一个数字来证明该字段被丢弃:

#!/bin/bash 
output="Th4is\nis 3\na 7\n2 string"
IFS='\'
words=(${output//[!0-9\\]/})
printf "%s\n" "${words[@]:1}"

忘记上面的版本,它适用于文字\ n ...

#!/bin/bash
output="Th4is
is 3\n
a 7
2 string"
tmp=(${output//[!0-9]/ })
printf "%d\n" "${tmp[@]:1}"

3
7
2

应该做