Reputation: 879
I have a text file which is of the following format:
{
Name: Me
Age:17
Qualification : Doctor
}
{
Name: You
Age:21
Qualification : Another Doctor
}
I need to copy the number in the Age lines, '17' and '21' in this case, to another file in this format:
17,21.
As you can see i am trying to create a File 2 CSV of the numbers in a certain field in File 1. I need to automate this using shell script. Kindly suggest a solution to this.
When I searched on Google, the 'sed' option turned up but I could not figure out a compact solution for this problem.
Thanks in advance for your time and contributions.
Upvotes: 1
Views: 796
Reputation: 58578
This might work for you (GNU sed):
sed '/\s*Age:\s*/H;$!d;x;s///;s//,/g' file
This appends the lines with Age:
to the hold space (HS) and deletes everything else. On end-of-file it swaps to the HS and removes the unwanted text replacing it with ,
's.
Upvotes: 2
Reputation: 208107
Here is a variation on Jotne's response with tidied up trailing comma:
awk -F: '/Age:/{r=r $2 ","}END{sub(/,$/,"",r);print r}' a
17,21
Basically, it builds up a result string in the variable "r" by looking for lines containing "Age" and then appending the second field on that line and adding a comma afterwards. At the end, it replaces a trailing comma (at the end of the line) with nothing, and then prints the result string "r".
Upvotes: 2
Reputation: 80211
@ECHO OFF
SETLOCAL
SET "number1="
(
FOR /f "tokens=1,2delims=: " %%a IN (q20072209.txt) DO IF "%%a"=="Age" (
IF DEFINED number1 (
CALL ECHO %%number1%%,%%b.
SET "number1="
) ELSE SET number1=%%b
)
)>newfile.txt
TYPE newfile.txt
GOTO :EOF
Not at all sure what is supposed to happen if there's more than 1 pair of data elements.
q20072209.txt
is the name of your input textfile and newfile.txt
will be produced.
Upvotes: 1
Reputation: 41460
Some like this?
awk -F: '/Age/ {printf "%s,",$2} END {print ""}' file1 >agefile
cat agefile
17,21,
Upvotes: 2