I have a two part problem using awk in bash, first to properly split linefeed delimited text, and second to use the output of awk in the same command line.
For the sake of an example, I would like to list the contents of the second subdirectory within a specific subdirectory.
Assume my directory structure is something like this:
$HOME/meals/dinner
/dinner/appetizer
/dinner/dish
I used the command below which returned text delimited by and ending in 0x0A
$ ls meals/dinner | awk '{split($0,a,"\\n"); print a[1]; }'
appetizer
dish
xxd output shows (00000000: 6170 7065 7469 7a65 720a 6469 7368 0a appetizer.dish.)
As a test, I tried this, and it worked.
$ echo "AAA
BBB" | awk '{split($0,a,"\\n"); print a[1]}'
AAA
$ echo "AAA
BBB" | awk '{split($0,a,"\\n"); print a[2]}'
BBB
What is my split doing incorrectly with the output of ls?
Second problem: Even if I extract the delimited directory name, I am not sure how to use it as part of a subsequently executed command on the same command line.
As a simple test, I request an example to ls the extracted directory by name.
Thank you.
Update: I have a workaround, though not exemplary. Here # is the index of a specific subdirectory within an ordered list of subdirectories.
find directory/. -maxdepth 1 -mindepth 1 -type d -printf '%f
' | head -n # | tail -n 1
However, @EdMorton has pointed out that *nix filenames allow linefeeds. For my purposes, the filenames are generated by a tool and won't have linefeeds but I would be thrilled to have a better solution.
Also, it became clear that my use of echo generated a false positive, and that my assumption that awk was treating
as an escape sequence was faulty.
A few commentors have asked what I am trying to do. Apologies that my original post was not clear.
I want to get a single-depth list of subdirectory names within a known directory, I want to get the name of the Nth subdirectory based on my script needs, and I want to use that subdirectory name (ideally) in the same command line to process the contents of that subdirectory.
- the name of the main directory is the same as its project
- there is a known subdirector, say "assets", containing an unknown number of subdirectories, each named uniquely based on a number unique to the system, like a GUID but not.
- within each uniquely named subdirectory of "assets" exists uniquely named and ordered based, but the subdirectory names (for reasons known only to the tool creator) are unknown - just that they are ordered partly by type, partly by a unique number.
- the Nth subdirectory in any main directory will always contain a certain file type
- Example:
project/assets/70137592/402938/*
<e.g. all the files of a type>
I have been assured the schema and numeric sort order of subdirectories within '70137592' will never change. :shrug:
question from:
https://stackoverflow.com/questions/65949065/how-do-i-split-a-linefeed-delimited-string-in-awk-and-use-its-output-on-the-same