awk - extracting pcap name from a string using shell script or gawk -
i have file pcap_list contains path of several pcap files eg.
./folder1/folder2/...../foldern/sample1.pcap ./folder1/folder2/...../foldern/sample2.pcap , on.... from want extract name of pcap files using shell script in linux. can let me know how can . though when used gawk 'begin {fs = "/"} {print $nf}' pcap_list worked fine. want in loop , wrote following script that.
#!/bin/bash pcap_list=$1 count=0 cat $pcap_list | while read pcap_path let count++ echo "$count $pcap_path" pcapname=($(gawk -v pcappath=$pcap_path 'begin {fs = "/"} {print $nf}' pcappath)) printf "pcapname =$pcapname" done it not working. can let me know how can that. appreciated. thanks.
the reason it's not working you're using variable name incorrectly on gawk command. is, it's trying process file called, literally, "pcappath". variable passing argument makes variable available inside gawk script, not filename argument.
in question, "it not working", don't how or include error messages. if had, gives information problem is.
regardless, fixing problem simple.
you can use basename mechanical snail suggests, or can fix gawk version (which show below), or can use pure bash version (which show below that).
pcapname=$(echo "$pcap_path" | gawk 'begin {fs = "/"} {print $nf}') also, there's no reason use set of parentheses create array.
here's pure bash version:
#!/bin/bash pcap_list=$1 count=0 while read -r pcap_path (( count++ )) echo "$count $pcap_path" pcapname=${pcappath##*/} printf '%s\n' "pcapname = $pcapname" done < "$pcap_list" you should habitually use lower case or mixed case variable names in order reduce chance of name collision shell or environment variables.
don't use cat application - redirect file done statement. 1 advantage avoids creating subshell variables retain values after while loop completed.
the -r option of read should used. causes read accept backslashes literally.
use (()) instead of let since it's more flexible.
use parameter expansion extract basename.
your printf (presumably) needed newline.
Comments
Post a Comment