I have ASCII file and I want to output the file name and a specific field from this file beside each other. For example:
The contents of the ASCII file "data1.txt" is as follow:

Name: John
Age: 90
Gender: Male
Date: 20160105

I have a very long list of folders. Inside every folder I have the file data1.txt. The files share the same design like how I showed before but the content is different.

In the parent folder I created I text file with the list of folders and I named it all.txt. Then I wrote the following bash script:

for i in $(cat $PAT/all.txt); do
sed -n '/Name:/p'   $PAT/$i/data1.txt | awk '{ print $2}'

How can I revise the previous code to print the following:

data1: John      
  • also, the filename is data1.txt , not data1. do you always want to print the first line, or how do you decide which is the specific line what you want to print ? do you want to loop/process certain files from a folder ? – mazs May 14 '16 at 17:30
  • I will re edit the question – user88036 May 14 '16 at 17:31
  • @ don_crissti. Yes. Thank you very much for any advice – user88036 May 14 '16 at 17:41
  • @ don_crissti.Exactly! – user88036 May 14 '16 at 17:44
  • Is it important that you use "print and awk"? Do you mean the shell's print command or awk's print command or something else? – Mikel May 14 '16 at 17:53

You don't need the all.txt file, sed, or a for loop. find and awk can do it all:

find /path/to/folder -name data1.txt -exec awk -F': ' '/^Name/ {print $2}' +

Using a field separator of : (colon followed by a space character) is the key to getting the output right (no leading space, supports one or more words in the second field)

If you want the filename in the output, change the awk script to something like this:

find ... -exec awk -F': ' '/^Name/ {print FILENAME": "$2}' +

I did the following and the code worked perfectly:

for i in $(cat $PAT/all.txt); do
echo -n "data1" 
sed -n '/Name:/p'   $PAT/$i/data1.txt | awk '{ print $2}'
  • 1
    Don't use PATH as one of your variables. All sorts of things will break if you do, as it's a reserved variable that holds the set of directories you search for executables. – roaima May 15 '16 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy