简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM