user46292
user46292

Reputation: 3

passing awk variable to bash script

I am writing a bash/awk script to process hundreds of files under one directory. They all have name suffix of "localprefs". The purpose is to extract two values from each file (they are quoted by ""). I also want to use the same file name, but without the name suffix.

Here is what I did so far:

#!/bin/bash

for file in *  # Traverse all the files in current directory.
   read -r name < <(awk ' $name=substr(FILENAME,1,length(FILENAME)-10a) END {print name}' $file) #get the file name without suffix and pass to bash. PROBLEM TO SOLVE!
   echo $name # verify if passing works.
   do
   awk  'BEGIN { FS = "\""} {print $2}' $file #this one works fine to extract two values I want.
   done

exit 0

I could use

awk '{print substr(FILENAME,1,length(FILENAME)-10)}' to extract the file name without suffix, but I am stuck on how to pass that to bash as a variable which I will use as output file name (I read through all the posts on this subject here, but maybe I am dumb none of them works for me).

If anyone can shed a light on this, especially the line starts with "read", you are really appreciated.

Many thanks.

Upvotes: 0

Views: 2508

Answers (2)

stark
stark

Reputation: 13189

To just take sbase name, you don't even need awk:

for file in * ; do
   name="${file%.*}"
   etc
done

Upvotes: 1

konsolebox
konsolebox

Reputation: 75458

Try this one:

#!/bin/bash

dir="/path/to/directory"

for file in "$dir"/*localprefs; do
    name=${file%localprefs}  ## Or if it has a .: name=${file%.localprefs}
    name=${name##*/}  ## To exclude the dir part.
    echo "$name"
    awk 'BEGIN { FS = "\""} {print $2}' "$file"  ## I think you could also use cut: cut -f 2 -d '"' "$file"
done

exit 0

Upvotes: 2

Related Questions