I have a file that contains may tab-separated columns in the following format
AAA BBB;CCC;DDD;E=10;F=20 GGG
XXX YYY;ZZZ;DDD;E=50;F=40 PPP
I need to print the values E
(or F
) using an UNIX command.
10
50
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityUse cut
to obtain the fourth field, then sed
to remove everything up to the equals sign:
cut -f 4 -d\; | sed 's/.*=//'
However, you mention tab-separated fields, though your sample lines separate fields by semicolons.
cut -f4 -d\; | cut -f2 -d=
exploits the similarities between structures. Handling the 5th original column is harder
Jan 24, 2021 at 0:00
With GNU grep, using PCRE (-P
) mode:
$ grep -Po '(?<=E=)\d+' file
10
50
or
$ grep -Po '(?<=F=)\d+' file
20
40
E=\K\d+
. The \K
resets the start of the match.
$ echo 'AAA BBB;CCC;DDD;E=10;F=20 GGG' | awk -F';' '{ print $4 }' | awk -F= '{ print $2 }'
10
$ echo 'XXX YYY;ZZZ;DDD;E=50;F=40 PPP' | awk -F';' '{ print $4 }' | awk -F= '{ print $2 }'
50
Or even easier:
$ echo 'XXX YYY;ZZZ;DDD;E=50;F=40 PPP' | awk 'match($0, /=[0-9]+/) { print substr($0, RSTART + 1, RLENGTH - 1) }'
50
$ echo 'AAA BBB;CCC;DDD;E=10;F=20 GGG' | awk 'match($0, /=[0-9]+/) { print substr($0, RSTART + 1, RLENGTH - 1) }'
10
Also with awk
you could try this"
cat file
AAA BBB;CCC;DDD;E=10;F=20 GGG
XXX YYY;ZZZ;DDD;E=50;F=40 PPP
E
awk -F'[=; ]' '{ print $6}' file
10
50
F
awk -F'[=; ]' '{ print $8}' file
20
40
If you don't care about the rest of the line, if you just want to find E=
or F=
wherever they appear, you could use sed
:
sed -e 's/.*E=//' -e 's/;.*//'
This deletes everything up to and including "E=
", and then deletes the ;
and everything following it. It assumes that every line does contain "E=
".
If you know that the E=
field always appears in a certain column (with the columns separated by tabs, or semicolons, or whatever), it might be preferable to first extract that column using cut
or the equivalent, then work on separating the E=
part from the value. You could do that using sed
as in @berndbausch's answer, or use a second invocation of cut
assuming =
-separated columns.
sed 's/.*;E=\([0-9]\+\);.*/\1/'
, without the second -e
?
=
character? Off the top of my head,awk
would be an easy tool to use for this as it allows you both process only lines with a certain text pattern, and extract data from delimited fields. Looks like you could specify a blank,;
, and=
as field separators.