3

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

AAAAAA|04|XXXXXXX|20170210-163119|||2.0|20170208||

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
4

This will do the job:

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

You can also use cut:

cut -d\| -f7 | cut -c1
2

Bash

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

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.

Expr

sep='|'
fld="[^$sep]*"
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

1

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.

Explanation

open('f').readlines()

will read the file per line, and

s.split('|')[6][0] 

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)

1

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
0

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.