How can I extract the 6 characters after Z in the following text line and put it into a file using grep, egrep, sed or awk?
B1_Site4_5aT4ZNHN691AQSB6B65_KYEC_SLT_2013-11-24-00-30_935985e7_100m_PASS1.tar
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 communityHow can I extract the 6 characters after Z in the following text line and put it into a file using grep, egrep, sed or awk?
B1_Site4_5aT4ZNHN691AQSB6B65_KYEC_SLT_2013-11-24-00-30_935985e7_100m_PASS1.tar
file="B1_Site4_5aT4ZNHN691AQSB6B65_KYEC_SLT_2013-11-24-00-30_935985e7_100m_PASS1.tar"
with GNU grep
when built with PCRE support (and with zsh
or recent versions of ksh93
or bash
for <<<
):
grep -oP '(?<=Z).{6}' <<< "$file" > file
with ksh93
, bash
or recent versions of zsh
:
tmp=${file#*Z} # remove chars up to the first Z
echo "${tmp:0:6}" > file
Just for fun, awk
awk -F Z '{print substr($2, 1, 6)}' <<< "$file"
expr B1_Site4_5aT4ZNHN691AQSB6B65_KYEC_SLT_2013-11-24-00-30_935985e7_100m_PASS1.tar : '.*Z\(.\{6\}\)' > file
Or just with the shell
string=B1_Site4_5aT4ZNHN691AQSB6B65_KYEC_SLT_2013-11-24-00-30_935985e7_100m_PASS1.tar
printf '%.6s\n' "${string#*Z}" > file
(the first one will consider the last Z followed by 6 characters, the second one the first; behaviour will vary if their not ZXXXXXX in there).
>>echo \
B1_Site4_5aT4ZNHN691AQSB6B65_KYEC_SLT_2013-11-24-00-30_935985e7_100m_PASS1.tar |
sed 's/.*Z\(.\{6\}\).*/\1/'
>>NHN691
Adding a >file
will put it in a file.
sed
is the right choice. However, put the '|' at the end of the echo
line, and you don't have to backslash the newline to get the pipeline continued.
sed
works on every line of its input, not the whole input, so somehow expr
is more appropriate (echo
has a few issues associated with it as well for arbitrary data).
Jan 10, 2014 at 22:35