Search code examples
awk

Print lines from their beginning to selected characters


I want to print lines from their beginning to selected characters.
Example:

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

Command:

 ./hhh.csh 03_input.txt c

Output:

a/b/i/c  
a/e/b/f/r/c  
a/b/c  
a/c   
a/e/f/c  
a/n/d/c

I use this code but in the condition $i ==a I don't see the values ​​being checked against the first value I assigned.

awk'  
BEGIN{  
ARGC=2  
 first = ARGV[2]  
}  
{  
for(i=1;i<=NF;++i){  
arr[i]=$i  
if($i == first){  
print arr[i]  
}    
}  
}' "$1" "$2"  

Solution

  • As awk is tagged, filter for a match on /c/, then print the substr from position 1 to position RSTART, which is where the pattern was found:

    # expecting the filename (e.g. 03_input.txt) on $1,
    # and the pattern (e.g. c) on $2
    awk -v pat="$2" 'match($0, pat) {print substr($0, 1, RSTART)}' "$1"
    
    a/b/i/c
    a/e/b/f/r/c
    a/b/c
    a/c
    a/e/f/c
    a/n/d/c
    

    Note: You may want to replace RSTART with RSTART+RLENGTH-1 if pattern longer than one character are expected.