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?


3 Answers 3


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

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/'

Adding a >file will put it in a file.

  • 1
    As an Aging Dinosaur, I believe 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.
    – user732
    Jan 10, 2014 at 22:03
  • 1
    @BruceEdiger, 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.