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?
source to share
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
source to share
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|'
}
source to share