Shell script extract 2 values ​​from all files?

I have a directory full of files like this:

[Location] state=California city=Palo Alto [Outlet] id=23 manager=John Doe 

I want to write a small script that outputs one line for each file as follows:

 John Doe,Palo Alto 

How can I do it? I suspect some grep and looping. So far, I:

 #!/bin/bash echo Manager,City > result.txt for f in *.config do cat "$f" | grep manager= >> result.txt cat "$f" | grep city= >> result.txt done 

but this, of course, is incomplete, since grep returns the entire string in its string, and I only need the part after the first = sign.

+4
source share
3 answers
 echo Manager,City > result.txt for f in *.config; do manager=$(awk -F= '$1=="manager" {print $2}' "$f") city=$( awk -F= '$1=="city" {print $2}' "$f") echo "$manager,$city" done >> result.txt 

awk -F= uses the equal sign as a field separator, and then checks for the required variables ( $1 ) and prints their values ​​( $2 ). $(cmd) captures the output of the command and displays lines that can be assigned to the two variables $manager and $city .

+2
source

Like John Kugelman’s answer , but using grep .

 echo Manager,City > result.txt for file in *.config; do name=$(grep -oP '(?<=manager\=).*' "$file") location=$(grep -oP '(?<=city\=).*' "$file") echo "$name,$location" done >> result.txt 
+2
source

You can do this with a single awk command according to the following transcript:

 pax> cat 1.config [Location] state=California city=Palo Alto [Outlet] id=23 manager=John Doe pax> cat 2.config [Location] state=Western Australia city=Perth [Outlet] id=24 manager=Pax Diablo pax> awk ' /^city=/ {gsub (/^city=/, "", $0); city=$0} /^manager=/{gsub(/^manager=/, "", $0); print $0 "," city} ' *.config John Doe,Palo Alto Pax Diablo,Perth 

Please note that this assumes that the city arrives in front of the manager, and that all files have both the city and the manager. If these assumptions are incorrect, the awk script becomes a little more complex, but it is still possible.

In this case, it becomes something like this:

 awk ' FNR==1 {city = ""; mgr = ""} /^city=/ {gsub (/^city=/, "", $0); city = $0} /^manager=/ {gsub (/^manager=/, "", $0); mgr = $0} {if (city!="" && mgr!=""){ print mgr "," city; city = ""; mgr = ""; }} ' *.config 

This is to make the order inappropriate. It dumps the city and manager variables to an empty line at the beginning of each file and simply saves them when it finds the corresponding lines. After each line, if both are installed, they print and clear them.

+1
source

Source: https://habr.com/ru/post/1490612/


All Articles