I have this script, I'm getting first letter of my directory name, and I wan't to get directory names that start with the same letter and write to textfile. The for loop is looping list of directory names I have in .txt file.

        for dirName in `cat $1 | tr ' ' '_' | awk '/ova/ && !/Nova/' `
                firstLetter=$(echo $dirName | head -c 1)

                mkdir "/opt/SOS/$dirName"
                awk '{ print length(), $0 | "sort -n" }' $1 | cut -f 2- -d ' ' | awk -v var="$firstLetter" '$1 ~ /^ *var/' >> "/opt/SOS/$dirName/seznam-obci-stejne-pismeno.txt"

I'm using Linux version 4.19.0-13-amd64 (debian-kernel@lists.debian.org) (gcc version 8.3.0 (Debian 8.3.0-6)) #1 SMP Debian 4.19.160-2 (2020-11-28)
Thank you for help

  • Ok, I did what I want by grep awk '{ print length(), $0 | "sort -n" }' $1 | cut -f 2- -d ' ' | grep "^$firstLetter" >> "/opt/SOS/$dirName/seznam-obci-stejne-pismeno.txt", but still I want to know how to do this in awk. – Brokolicový Džuß Feb 18 at 20:10
  • 2
    The question is not clear. Why are you assuming you even need AWK? Are you looking for a solution to your problem or is the idea of showing broken code? You might disagree with the broken code part, however, reading the for dirName in cat ... seems like really broken to me. Please tell us how your file with directory names looks like and what your End Goal is. – Valentin Bajrami Feb 18 at 20:37
  • You are parsing the same file multiple times. This should be able to be accomplished with a single awk program. Show some sample input data and what the output should be. – glenn jackman Feb 18 at 22:34

Inside /.../ awk does not interpolate variables -- it's literal text in there.

Choose one of:

awk -v letter="$firstLetter" '$1 ~ "^" letter'
awk -v letter="$firstLetter" 'index($1, letter) == 1'
awk -v letter="$firstLetter" 'substr($1, 1, 1) == letter'

Note that, due to the default field separator, a field in awk will never start with spaces.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.