I have a pipe(|) separated string, I need to find the first character in the 7th column of that pipe-separated string


Expected output : 2

  • expected output is 2 or 2.0? – Rakesh.N Mar 6 '17 at 11:37
  • use substr on $7 – Sundeep Mar 6 '17 at 11:38
  • sed -ne 's/|/\n/6; s/.*\n\(.\)/\1\n/; P' – user218374 Mar 6 '17 at 11:43

This will do the job:

awk -F "|" '{print(substr($7,1,1))}' input.file.txt

You can also use cut:

cut -d\| -f7 | cut -c1


IFS='|' read -r -a x <<< "$str"
echo "${x[7]:0:1}"

read command uses the contents of $str and splits them on the pipe | char and fills them into an array (-a) named x. Then we extract one character from the beginning of the 7th field.


perl -F'\|' -pale '($_) = $F[6] =~ /./g' <<< "$str"

-F => field separator, -p => autoprint mode, -a => autosplit turned on, -l => set up the record separator(RS) to \n and ORS to \n.

7th field $F[6] is evaluated in a list context and as /./g and returns individual chars, of which the first is picked and stored in the $_ which due to the autoprint will take it to stdout.


fld7=$(yes "$fld$sep" | sed 7q | tr -d '\n')
expr "$str" : "$fld7\(.\)"

Here we construct the command so that expr does it's job under the hood.

echo "$fld"; # => [^|]* echo "$fld7"; # => [^|]*[^|]* .... 7 times


Using python3, assuming column 7 exists on all lines in the file:

python3 -c "[print(l.split('|')[6][0]) for l in open('f').readlines()]"

> 2

Where 'f' is the (full) path to the file, in single quotes.



will read the file per line, and


will split the line by the delimeter |, and subsequently print the first character of the 7th column (where 0 is the index of the first column)


To study the interesting sed behavior

sed 's/\(\([^|]\?\)[^|]*|\)\{7\}.*/\2/' input.file.txt

or to reduce escaping

sed -r 's/(([^|]?)[^|]*\|){7}.*/\2/' input.file.txt

or to avoid regex

sed '/\n/{s/./\n/2;P;d;};s/|/\n/6;s/$/\n/;D' input.file.txt

This may help:

awk -F'[|.]' '{print $7}' filename.txt
  • 1
    This only works for cases where i) there is only 1 . on the line and ii) that . is the 2nd character of the 7th field. – terdon Mar 6 '17 at 12:03

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.