Billy Grande
Billy Grande

Reputation: 587

Reading a string variable in shell bash line by line and get a number of each line

I wanna do what the title says. In addition it would be desirable to skip the first line. I have this code

#!/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

But doesn't wotk. Any ideas? Thanks in advance.

Upvotes: 0

Views: 108

Answers (1)

Deleted User
Deleted User

Reputation: 2541

I modified your input string called "output" by adding a number in the first field (line), to demonstrate that that field gets discarded:

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

Forget about the above version, it works on literal \n ...

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

3
7
2

that should do

Upvotes: 1

Related Questions