1

i am trying to find a way of searching a file for string, it needs to work by searching then file and if any line in the file begin with what i am searching for, then take that whole line and save it as variable so i can using it later on kick off another command.

i have try this in python but i want to find a way in bash

def f(inputpara,substringpara):
   temp_log=""
   for item in inputpara.split("\n"):
    if  substringpara in item :
             temp_log=item.strip()
  return  temp_log

thanks i was able to get it working

IFS=$'\n' lines=( $(grep 'string*' textout.txt) )

    for i in "{lines[@]}"
            do
             echo ${lines[@]}
    done
3
  • Perhaps man grep? Jun 27, 2016 at 10:54
  • Do you want only the first matching line? An array containing all of them? Any, ie. don't care which?
    – JigglyNaga
    Jun 27, 2016 at 12:59
  • well in the text file there are only 10 line and the lines that i want to pull out are all unique, so it should work with the first matching line
    – soad666p
    Jun 27, 2016 at 14:04

1 Answer 1

1

Use grep to find the string at the start of the line and an array to save the results:

IFS=$'\n' lines=( $(grep '^string' file.txt) )
  • grep '^string' file.txt finds the string string at the start of lines of file file.txt

  • The array lines contains the matched lines, the IFS=$'\n' makes each line an array element

Now you can iterate over the results using regular array operations.

For example, to find the number of lines found:

${#lines[@]}

First element:

${lines[0]}

Second element:

${lines[1]}

Iterate over the elements using for loop:

for i in "{lines[@]}"; do ....; done
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .