I want to explain behavior of your code
awk'
BEGIN{
ARGC=2
first = ARGV[2]
}
{
for(i=1;i<=NF;++i){
arr[i]=$i
if($i == first){
print arr[i]
}
}
}' "$1" "$2"
you are using for
loop to iterate over fields, but you do not set FS
(field separator) so GNU AWK
assumes you are dealing with file where fields are sheared by one-or-more white-space characters, which for file like
a/b/i/c/f/d
a/e/b/f/r/c
a/f/d/g
a/n/m/o
a/o/p/d/l
a/b/c/d/e
a/c/e/v
a/d/l/k/f
a/e/f/c
a/n/d/c
means each line has 1 file (awk '{print NF}' file.txt
would output just 1s).
You might exploit GNU AWK
field splitting to get your task done following way
awk -v character="c" 'BEGIN{FS=character;ORS=FS"\n"}NF>1{print $1}' file.txt
which for file as above gives output
a/b/i/c
a/e/b/f/r/c
a/b/c
a/c
a/e/f/c
a/n/d/c
Explanation: I inform GNU AWK
that provided character should be treated as field separator (FS
) and that output row separator (ORS
) which is added after each print is said character followed by newline. For each line with more than 1 field I print
1st field. Disclaimer: this solution assumes that character variable always hold exactly 1 character, if you are unable to meet this requirement ignore this answer entirely.
(tested in GNU Awk 5.1.0)
sh
, even when they are completely trivial. (Separately, probably don't put any extensions on your interactive scripts; you don't need to know or care which languagels
is implemented in, and nor should it matter for tools of your own.) – Mmeawk
and the single quote. – Mme/
-separated string, or up to a string that matches a regexp or something else? Your current answers would do different things with different characters, different input, etc. and I strongly suspect they don't do what you actually want, you just haven't thought about or tested with the right input yet to discover the problems. See #65621825 for considerations and then clarify your requirements and provide more realistic sample input/output, maybe in a new question – Putscher