Hi All,
We have a requirement of picking nth position value by using cut command. value would be delimited by any symbols. We have to pass delimited value and postition to get the value in a string.
ex.
echo "A,B,C,D,E" |cut -d "," -f3
echo "A|B|C|D|E"|cut -d "|" -f2
Kindly frame the unix command to to get both output in a single command by passing delimited value and position dynmically.
Thanks in advance.
Moderator comments were removed during original forum migration.
Here is a solution in awk. Pass delimiter plus required position.
$ cat kk230689
awk -v A="$*" '
BEGIN { split(A, want)}
{ for (i in want) {
p=substr(want,2)
v=substr(want,1,1)
if (split($0, flds, v) >= p)
print flds[p]
}
}'
$ cat infile
A,B,C,D,E
A|B|C|D|E
$ ./kk230689 ',3' '|2' < infile
C
B
Thanks Chubler,
You have written both o/p in single query , but our requirement is to pass the delimited value and position as a paramter and get respective result.
Example:
Input parameter will receive deifference format.
option1 :
A,B,C,D,E,F
Option2 :
A|B|C|D|E
for the above option , unix command should be static by passing paramter as delimited and position.
my workaround code :
echo "A,B,C,D,E"|cut -d "," -f2
echo "A|B|C|D|E"|cut -d "|" -f3
"," -f2 - these value should be dynamic..
Can you plz help on this.
apmcd47
September 11, 2018, 5:46am
5
If I read you correctly you wish to dynamically change the delimiter used by cut:
DELIM=,
echo "a,b,c,d,e" | cut -d "$DELIM" -f 3
DELIM="|"
echo "A|B|C|D|E" | cut -d "$DELIM" -f 2
Or is it a case you don't know whether the delimiter will be comma, a pipe or something else?
echo "A|B|C|D|E" | tr '|;' ',,' | cut -d "," -f 2
echo "a;b;c;d;e" | awk -F"[,|;]" '{print $3}'
All the above are simplistic examples.
Andrew
1 Like
RudiC
September 11, 2018, 10:03am
6
Why not a function with what you already have?
CUTDLFLD() { cut -d"$1" -f"$2" ${3:--}; }
Call like
echo "a,b,c,d,e" | CUTDLFLD "," "3"