Easiest way to get data back from string to file

I have a file tmp.info

that is formatted like this:

foo..............bar
alligator........bear
cat..............dog

      

and I would like to make a small shell command in bash that returns the second line in the line when the first is passed to the function. For example, something like:

#!/bin/bash

get_from_info_file() {
cat $1 | grep $2 | grep ????????
}

echo `get_from_info_file tmp.info alligator`

      

should return:

>>> bear

      

What's the most elegant way to do this?

+3


source to share


6 answers


You can use awk for example:

get_info_from_file() {
    awk -F'\\.+' -v search="$2" '$1 == search { print $2 }' "$1"
}

      

This sets the field separator to one or more .

and sets the variable search

using the second argument passed to the function. If the first field $1

is equal to the search string, print the second field.



Testing using the file in your question:

$ get_info_from_file tmp.info alligator
bear

      

+7


source


Declare your function like this:

#!/bin/bash

get_from_info_file() {
    sed -n "s/$2\.*\(.*\)/\1/p" "$1"
}

      

Call it filename

as the first parameter and the desired key as the second parameter:



echo `get_from_info_file tmp.info alligator`

      

Prints:

bear

      

+3


source


This function implements what you need:

function getValue(){
     local value=$1
     local file=$2
     grep ^$value\. $file | tr -s '.' | cut -d'.' -f2
}

      

+1


source


A (not elegant) bash version only:

#!/bin/bash
get_from_info_file() {
  file=$(<$1)
  i1=${file##*$2}
  i2=${i1%%[:punct:]*}
  echo ${i2##*\.}
}

echo `get_from_info_file tmp.info alligator`

      

+1


source


The easiest way:

line=$(cat $1 | grep $2) 
array=(${line//./ } ) 
echo ${array[1]} 

      

  • grep a string and store it in a variable
  • use variable substitution replace. into space, wrap it in an array
  • print the second element of the array
+1


source


using grep

(notification \K

):

get_from_info_file() {
    grep -Po "$2\.+\K\w+" "$1"
}

      

usig perl

:

get_from_info_file() {
    perl -nle 'print $1 if /'"$2"'\.*(.*)/' "$1"
}

      

using expr

the match operator :

:

get_from_info_file() {
    a=$(grep "$2" "$1")
    expr "$a" : "^\.*\(.[a-z]*\)"
}

      

using sed

:

get_from_info_file() {
    grep "$2" "$1" | sed -r 's|.*\.+(.*)|\1|'
}

      

0


source







All Articles